At work, we’ve been having a religious debate (I prefer to call it that because I’m losing) about whether to use href=”javascript:void(0);” or href=”#” in links with javascript events attached. I’ve been searching for the consensus on the web and thought I’d share. In general, the consensus is that “javascript:void(0)” is bad but I can’t find any authoritative source for it. Many references point out the simple solution to href=”#” making you jump to the top of the page is just to return false from your JS. D’oh!
- http://stackoverflow.com/questions/134845/href-for-javascript-links-or-javascriptvoid0
- http://www.javascripttoolbox.com/bestpractices/#onclick
- http://forums.digitalpoint.com/showthread.php?t=981269
- http://www.sitepoint.com/forums/showthread.php?t=565853
- http://blog.reindel.com/2006/08/11/a-hrefjavascriptvoid0-avoid-the-void/
(actually dislikes both alternatives)
There’s an agonizing reference to a MS article that might be authoritative in that last article, but no url given. An interesting alternative suggested in a comment on the first article is not to attach “pure” js events (i.e. there’s no actual fallback link) to <a> tags at all. Another viable (standards-based) approach is to use <a> tags without a href (and style the cursor to be a pointer over those links). I’d sure love to hear other people’s opinions.

4 responses so far ↓
1 Andrew Tunnell-Jones // Feb 16, 2009 at 7:12 pm
Perhaps you should revise the question.
I get annoyed when I open a new-tab to discover the link was href=”javascript:void(0);” on search result pages. Especially if I’ve just opened a bunch of tabs and closed the first.
On the other hand if I’m filling in a form I’m not likely to close the original tab and I’d rather arrive nowhere (well actually I’d rather that whatever I clicked looked buttonish rather than linkish so I wouldn’t attempt to open it in a new tab).
I also get annoyed if a form-widget that opens in a new window scrolls me away from that section of the page due to the JS call not returning false; unless there’s a need for me to back at the start.
What is least annoying to the people using your site?
2 Eli White // Feb 17, 2009 at 9:54 am
I personally dislike javascript:void(0); just because it’s messy, it’s long, people see it in the status bar and it means nothing.
I therefore prefer to have href=”#” and return false. Or to just attach onclick events to random things. The latter having issues of being not so well supported in older browsers.
Eli
3 Dan // Mar 19, 2009 at 9:07 am
Just attach your event to the element at hand directly. like so:
<div onclick=”foo();”> Text </div>
4 Maurice // Feb 4, 2011 at 11:06 am
if you closed some tab you can always reopen it, CTRL + SHIFT + T
I prefer to use click me with style{ cursor: pointer; }
and jQuery like: $(“.profile”).bind(‘click’, handler)
in that way i can attach event to all elements with class profile
Leave a Comment