Reputation: 16095
When I want to prevent default behaviour of anchor tag I`m using
<a href="javascript:void(0);">link</a>
Which is the most effective solution ?
Upvotes: 57
Views: 86835
Reputation: 3794
I know it's an old thread but here is what I use often
<a href="javascript:void(0);">link</a>
<a href="javascript:;">link</a>
Upvotes: 7
Reputation: 49
Here is very easy way to stop this.
( function( $ ) {
$( 'a[href="#"]' ).click( function(e) {
e.preventDefault();
} );
} )( jQuery );
Upvotes: 3
Reputation: 342635
An example of a gracefully degrading solution:
<a href="no-script.html" id="myLink">link</a>
<script>
document.getElementById("myLink").onclick = function() {
// do things, and then
return false;
};
</script>
Demo: http://jsfiddle.net/karim79/PkgWL/1/
Upvotes: 39
Reputation: 129792
If you never want for the browser to follow the link anywhere, I'd say what you've got is the simplest, safest solution.
Sure, there are heaps of other solutions you could apply with javascript, but most other ways may fail when
return false;
or preventDefault
that might be at the end of the statement, will not be executed, and the browser will follow the link, if only to #
.Upvotes: 10
Reputation: 6518
This is a nice approach, if you're using jquery you can also do:
<a id="link" href="javascript:void(0)">link</a>
<script type="text/javascript">
$("#link").click(function(ev) {
ev.preventDefault();
});
</script>
preventDefault can be useful also to prevent submitting form
Upvotes: 40
Reputation: 66389
You can also have this:
<a href="#" onclick="return false;">link</a>
Upvotes: 21