Using an anchor as a javascript action, what should be the link?

I saw (and used) the code so that the link repeatedly triggered a javascript action in my life, but I never came to the firm conclusion whether the href attribute should be empty or #. Do you have any preferences anyway, and if so, why?

<a href="" onclick="javascript: DoSomething();">linky</a> 

or

 <a href="#" onclick="javascript: DoSomething();">linky</a> 
+4
source share
5 answers

You must have something for the href attribute, otherwise the browser will not consider it as a link (for example, make it focal or give it an underline) - why the use of "#" has become common.

In addition, the contents of the event attributes ( onclick , onmouseover , on... ) are already considered as javascript: you do not need to enter it using javascript:

So, given your example, the best way to do this is inline (which is perhaps not the best way), as follows:

 <a href="#" onclick="DoSomething(); return false">linky</a> 
+8
source

Make a Href discussion for Javascript: "#" or "javascript: void (0)" links? .

In addition, leaving the href space blank, the browser will not use the cursor cursor when the user navigates, although you can fix this with CSS.

+6
source

I always use # as having javascript: inside html attributes, they are generally considered bad practice these days.

Having said that, you should try to refrain from using the onclick = attributes and use javascript listeners in external .js files instead.

For example, you are using jQuery ..

 $(".link").click(function(e) { e.preventDefault(); DoSomething(); }); 
+1
source

Why not point href to the page, explaining that they have JavaScript disabled and they need to enable it in order to get the missing functionality?

Since the link will only be executed when javascript is turned off, let it be something informative!

Also remember that people sometimes visit such links, and the OnClick event does not fire, so if you can get them a page that works without the need for javascript, this will be perfect.

0
source

In such cases, when you intend not to provide a parameter other than javascript, I prefer:

 <a href="javascript:// open xxx widget" onclick="DoSomething();">linky</a> 

That way you can at least provide a textual description of the plan as a JavaScript comment.

0
source

All Articles