Anchor without href

What is the best way to cross to make an anchor without href (javascript-driven) behave like a real anchor? The most obvious is to use # as a binding, but this will cause the page to switch ...

+7
javascript html
source share
5 answers

A do-nothing link that doesn't even jump:

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

Update:. As the linked document pointed out (marked by Ambrosia), since void(0) returns undefined , it is better to write the code above:

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

Unless, of course, undefined has not been redefined.

+17
source share

You must return false from the click handler associated with the anchor. Given HTML:

 <a id="example" href="/whatever"/> 

JS should look like this:

 document.getElementById('example').onclick = customAnchorReturn; function customAnchorReturn() { // do stuff return false; } 

or using jQuery:

 $('a#example').click(function(){ // do stuff return false; }); 

This way, JS will be unobtrusive, and if JS is disabled, the anchor will work.

+6
source share

They will not jump:

 <a href="#null">Click</a><a href="#n">Click</a> <a href="#undefined">Click</a> 

They, however, destroy the soul and are extremely ugly.

+5
source share

If you are responding to a click event, just make sure you return false and that everything in href will be ignored by #hash or another URL.

 <a href="#anything" onclick="doSomething(); return false;">link</a> 
+3
source share

Perhaps this is also normal:

 <a href="javascript:;">link</a> 
+1
source share

All Articles