So, when you are doing some JavaScript things with an <a />
tag and if you put href="#"
as well, you can add return false at the end of the event (in case of inline event binding) like:
<a href="#" onclick="myJsFunc(); return false;">Run JavaScript Code</a>
Or you can change the href attribute with JavaScript like:
<a href="javascript://" onclick="myJsFunc();">Run JavaScript Code</a>
or
<a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a>
But semantically, all the above ways to achieve this are wrong (it works fine though). If any element is not created to navigate the page and that have some JavaScript things associated with it, then it should not be a <a>
tag.
You can simply use a <button />
instead to do things or any other element like b, span or whatever fits there as per your need, because you are allowed to add events on all the elements.
So, there is one benefit to use <a href="#">
. You get the cursor pointer by default on that element when you do a href="#"
. For that, I think you can use CSS for this like cursor:pointer;
which solves this problem also.
And at the end, if you are binding the event from the JavaScript code itself, there you can do event.preventDefault()
to achieve this if you are using <a>
tag, but if you are not using a <a>
tag for this, there you get an advantage, you don't need to do this.
So, if you see, it's better not to use a tag for this kind of stuff.
<a href="javascript:void(0)" onclick="myJsFunc();">
makes absolutely no sense. If you must use thejavascript:
psuedo-protocol, you don't need theonclick
attribute as well.<a href="javascript:myJsFunc();">
will do just fine. – Wesley Murch Jun 2 '13 at 17:41myJsFunc()
has a return value, your page will break. jsfiddle.net/jAd9G You'd still have to usevoid
like so:<a href="javascript:void myJsFunc();">
. But then, the behavior would still differ. Invoking the link via context menu does not trigger theclick
event. – gilly3 Jul 31 '13 at 0:24<a href="javascript:;" onclick="myEvent()"
? – 3k- Nov 20 '13 at 12:12javascript:;
is a lot quicker to type thanjavascript:void(0)
– Mike Causer Dec 12 '13 at 12:26<a>
tag if what you want to do is NOT to open another page via native browser feature but rather have some javascript 'action' to be triggered? simply using aspan
tag with a class ofjs-trigger
would probably much better". Or am I missing something? – Adrien Be Aug 14 '14 at 14:28