The dangers of embedding the notorious “void(0)” JavaScript code in the href attribute of the “a” tag
April 8th, 2009 | Published in javascript | 4 Comments
I recent ran into an interesting IE bug involving the following bit of html code:
<a href="javascript: void(0);" onclick="dosomething();">click me</a>
I honestly did not write this one but I will leave names out of this to protect the innocent =)
The void(0) JavaScript code is usually used to prevent loading or reloading of the page when the user clicks the link.
What we were trying to do here was have the dosomething JavaScript function execute when a user clicks on the link. This works fine in FireFox, Chrome, Safari but not IE. When a user clicks on the link in IE, nothing happens: i.e. (no pun intended) the JavaScript does not execute.
It took us a good amount of time to realize what the issue was with IE. It turns out that the void(0) function was preventing the onclick event to fire.
Although it may not be pretty, this is what we ended up doing and it appears to be cross-browser friendly:
<a href="<?=$_SERVER['PHP_SELF'];>#" onclick="dosomething();">click me</a>
Anyway, I hope this helps someone out there in the universe.
Share with a friend:Customize message
April 28th, 2009 at 10:26 pm (#)
Alternatively, you could use onclick with rather than and you won’t have to worry about the user being redirected anyplace or use the # in the href attribute.
[Reply]
May 3rd, 2009 at 10:14 am (#)
You don’t need to use PHP for that; just use href=”#” for that purpose. But this has the annoying side effect of snapping the cursor up to the top of the page. This can be cured by altering the onclick to return false:
a href=”#” onclick=”dosomething(); return false;”
Alternatively, have dosomething() return false, and use
a href=”#” onclick=”return dosomething();”
Personally, I prefer to use this format:
a href=”javascript:dosomething()”
This doesn’t navigate away from the page in modern browsers – and let’s face it, who cares about supporting Netscape 4.04 these days? Browsers that old are pretty much not-found, if you’ll excuse the pun!
[Reply]
August 5th, 2009 at 7:21 am (#)
I think the best way to do this is
href=”alternativelink” onclick=”dosomething(); return false;”
If someone has javascript enabled, dosomething() will be executed.
If javascript was disabled by the user, you provide an alternative with alternativelink. This is especially important, if you want to open a new page/image in a new window for example. Many people want to open the page or image in a new tab and use middle click on the link. But this only works if you provide alternativelink.
[Reply]
Knix reply on August 5th, 2009 7:28 am:
You are right. There are actually a lot of things wrong with this post and I do regret writing it. Using ‘#’ is definitely not the way to go. I will probably rewrite this one day using your recommendation amongst other versions. Thanks for your feedback.
[Reply]