I personally use them in combination. For example:
HTML
<a href="#">Link</a>
with little bit of jQuery
$('a[href="#"]').attr('href','javascript:void(0);');
or
$('a[href="#"]').click(function(e) {
e.preventDefault();
});
But I'm using that just for preventing the page jumping to the top when the user clicks on an empty anchor. I'm rarely using onClick and other on
events directly in HTML.
My suggestion would be to use <span>
element with the class
attribute instead of
an anchor. For example:
<span class="link">Link</span>
Then assign the function to .link
with a script wrapped in the body and just before the </body>
tag or in an external JavaScript document.
<script>
(function($) {
$('.link').click(function() {
... code to execute ...
});
})(jQuery);
</script>
*Note: For dynamically created elements, use:
$('.link').on('click', function() {
... code to execute ...
});
And for dynamically created elements which are created with dynamically created elements, use:
$(document).on('click','.link', function() {
... code to execute ...
});
Then you can style the span element to look like an anchor with a little CSS:
.link {
color: #0000ee;
text-decoration: underline;
cursor: pointer;
}
.link:active {
color: red;
}
Here's a jsFiddle example of above aforementioned.
<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