Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HREF link that targets nothing, does not want to use hash or void(0)

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?

like image 776
Mattis Avatar asked Jun 29 '11 00:06

Mattis


4 Answers

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
like image 81
user113716 Avatar answered Oct 19 '22 03:10

user113716


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.

like image 31
Eevee Avatar answered Oct 19 '22 02:10

Eevee


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.

like image 3
RobG Avatar answered Oct 19 '22 03:10

RobG


You can use preventDefault, for instance:

$('#foo').click(function(e){
    // Do stuff
    e.preventDefault();
});
like image 1
Grant Thomas Avatar answered Oct 19 '22 03:10

Grant Thomas