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.
$('#foo').click(function(e){
e.preventDefault();
// Do stuff
});
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 href
to handle graceful degradation.
What's the minimum definition of a function that does nothing?
Here's a no-op function:
var noop = function(){};
...or since you're using jQuery, you can use the jQuery.noop()
[docs] method, which also is just an empty function.
$.noop
Ideally, the link should link to a page that replicates the JavaScript functionality for users without JS enabled. Then preventDefault
would prevent the actual navigation, as the other answers have indicated.
If that doesn't make sense in this case, note that the href
attribute is optional. You can just leave it off entirely.
This is an inappropriate use of a link, you should be using a button or some other element that indicates that clicking will make something happen but not navigation.
You can use preventDefault
, for instance:
$('#foo').click(function(e){
// Do stuff
e.preventDefault();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With