A HREF link that doesn't target anything doesn't want to use a hash or void (0)

I have a link that I want to click in order to trigger a piece of jQuery code.

I currently have

<a href="#" id="foo">Link</a> 

and

 $('#foo').click(function(){ // Do stuff }); 

which works well. But I always hated using a hash that way. The page flicker and hash are added to the page URL.

One option is to use

 <a href="javascript:void(0);" id="foo">Link</a> 

but I also don’t like to see this piece of code in the browser status bar. It looks sticky.


What I would prefer is an explanatory javascript placeholder that does nothing, e.g.

 <a href="javascript:zoom();" id="foo">Link</a> 

which actually works, but throws a ReferenceError in the javascript console since there is no such function. What is 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

+7
source share
4 answers

Use the event.preventDefault() [docs] method.

 $('#foo').click(function(e){ e.preventDefault(); // Do stuff }); 

This will prevent a hash effect on click. Or get rid of the hash and use CSS to style it.

In addition, you can provide the actual url for href to handle competent degradation.


What is the minimum definition of a function that does nothing?

Here is the no-op function:

 var noop = function(){}; 

... or since you are using jQuery, you can use jQuery.noop() [docs] , which is also an empty function.

 $.noop 
+15
source

Ideally, the link should link to a page that replicates JavaScript functionality for users without JS enabled. Then preventDefault will interfere with the actual navigation, as other answers pointed out.

If this does not make sense in this case, note that the href attribute is optional. You can just leave it completely.

+3
source

This is improper use of the link, you should use a button or some other element that indicates that the click will do something, but not navigation.

+3
source

You can use preventDefault , for example:

 $('#foo').click(function(e){ // Do stuff e.preventDefault(); }); 
+1
source

All Articles