Prevent anchor behaviour

Javascript

Javascript Problem Overview


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 ?

Javascript Solutions


Solution 1 - Javascript

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/

Solution 2 - Javascript

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

Solution 3 - Javascript

You can also have this:

<a href="#" onclick="return false;">link</a>

Solution 4 - Javascript

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

  • The DOM is not completely loaded, if the event is assigned at DOMReady or later, which is common.
  • A click event listener handles the link (which is common where you want links not to be followed by the browser). If an error occurs in the javascript that handles the click, the 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 #.

Solution 5 - Javascript

I know it's an old thread but here is what I use often

Instead of this:

<a href="javascript:void(0);">link</a>

This also can work:

<a href="javascript:;">link</a>

Solution 6 - Javascript

Here is very easy way to stop this.

( function( $ ) {
   $( 'a[href="#"]' ).click( function(e) {
      e.preventDefault();
   } );
} )( jQuery );

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNickView Question on Stackoverflow
Solution 1 - Javascriptkarim79View Answer on Stackoverflow
Solution 2 - JavascriptCharles OuelletView Answer on Stackoverflow
Solution 3 - JavascriptShadow Wizard Says No More WarView Answer on Stackoverflow
Solution 4 - JavascriptDavid HedlundView Answer on Stackoverflow
Solution 5 - Javascriptankit sutharView Answer on Stackoverflow
Solution 6 - JavascriptMusarrofView Answer on Stackoverflow