views:

27

answers:

2

If I have a function like this:

function foo()
{
    //...
    return false;
}

I can call it like this:

<a href="#" onClick="foo()">Run Foo</a>

However, in all browsers, this puts an # in the URL which I do not want.

So instead I do this:

<a href="javascript:foo()">Run Foo</a>

Which works fine in chrome but in IE it loads a page containing the string false.

Whats the best practice here?

+2  A: 

You don't need the javascript: protocol.

<a href="#" onclick="foo(); return false">Run Foo</a>

is all you need.

wrumsby
I se no reason for this to have been down-voted. +1
LeguRi
it seems like someone just blanket down-voted every answer.
John Isaacks
A: 

Like @wrumbsy says...

You don't need the javascript: protocol.

<a href="#" onclick="foo(); return false">Run Foo</a>

... but this means you don't need an anchor <a> either. Only use anchors for hyperlinks; not for JS-enhanced interactivity.

A span will work just as well, with cursor:pointer; CSS property:

<span style="cursor:pointer;" onclick="foo(); return false">Run Foo</span>
LeguRi
But doesn't Google treat anchors differently then spans?
John Isaacks
How so? I'd say, yes, Google does, but that's exactly why you wouldn't want to use an anchor.
LeguRi
@John Isaacks - ... but it's less relevant for SEO and more relevant to accessibility.
LeguRi
Ahh, gotcha. Thanks.
John Isaacks