Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent anchor behaviour

Tags:

javascript

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 ?

like image 704
Nick Avatar asked Dec 08 '10 12:12

Nick


People also ask

Can anchors be disabled?

Yes, disabled isn't supported attribute by the anchor tab, but the CSS attribute selector does find it and so does jQuery's.


3 Answers

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/

like image 190
karim79 Avatar answered Oct 19 '22 09:10

karim79


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

like image 42
Charles Ouellet Avatar answered Oct 19 '22 09:10

Charles Ouellet


You can also have this:

<a href="#" onclick="return false;">link</a>
like image 19
Shadow Wizard Hates Omicron Avatar answered Oct 19 '22 11:10

Shadow Wizard Hates Omicron