I personally use them in combo e.g.
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 top when user clicks on 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 anchor e.g.
<span class="link">Link</span>
Then assign function to .link
with script wrapped in body and just before the </body>
tag or in external JS 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 span element to look like anchor with little CSS
.link {
color: #0000ee;
text-decoration: underline;
cursor: pointer;
}
.link:active {
color: red;
}
Here's a FIDDLE example of above aforementioned.
onclick=
. Using jQuery for example might look "lightweight" for its size ($('#foo').click(doSomething);
), but the amount of work and function calls that this causes is immense. – Camilo Martin May 27 '13 at 0:25<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