SiberianGuy
SiberianGuy

Reputation: 25302

Anchor without href

What is the best crossbrowser way to make anchor without href (javascript-driven) behave like real anchor? The most obvious one is to use # as anchor but it makes page jump...

Upvotes: 10

Views: 16407

Answers (5)

mr.b
mr.b

Reputation: 4962

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

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

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

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

Unless, of course, undefined has been re-defined.

Upvotes: 20

sebarmeli
sebarmeli

Reputation: 18275

You should return false from the click handler associated to the anchor. Given the HTML:

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

the JS should look like:

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

or using jQuery:

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

In this way, the JS will be unobtrusive and in case JS is disabled the anchor will still work.

Upvotes: 7

M&#237;ng
M&#237;ng

Reputation: 2608

Maybe this is OK too:

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

Upvotes: 2

great_llama
great_llama

Reputation: 11729

If you're reacting to the click event, just make sure you return false and whatever is in the href, whether a #hash or other url, will be ignored.

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

Upvotes: 4

karim79
karim79

Reputation: 342635

These will not jump:

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

They are, however, soul destroying and extremely ugly.

Upvotes: 9

Related Questions