I have a link that I want to be able to click to trigger a piece of jQuery code.
Currently I have
<a href="#" id="foo">Link</a>
and
$('#foo').click(function(){
// Do stuff
});
which works well. But, I have always hated using hash in this way. The page flickers and the hash is added to the page url.
One alternative is to use
<a href="javascript:void(0);" id="foo">Link</a>
but I also dislike seeing that piece of code in the browser status bar. It looks tacky.
What I’d rather have is an explanatory javascript placeholder that does nothing, like
<a href="javascript:zoom();" id="foo">Link</a>
which actually works, but throws an ReferenceError in the javascript console since there are no such function. What’s the minimum definition of a function that does nothing?
Are there any other alternatives?
Should I just skip the link and use something like
<span id="foo" style="cursor:pointer;cursor:hand;">Link</span>
instead?
Use the
event.preventDefault()[docs] method.This will prevent the hash from having any effect when you click. Or get rid of the hash, and use CSS to style it.
Also, you can provide an actual url for the
hrefto handle graceful degradation.Here’s a no-op function:
…or since you’re using jQuery, you can use the
jQuery.noop()[docs] method, which also is just an empty function.