There are plenty of occasions when coding JavaScript events where you simply need to call a function, for which an entire event registration model is too lengthy. The most commonly used method is to bind your event to an anchor link. The user clicks and the onclick event is fired, calling a reference to a function.
Because the user isn’t actually visiting a URL, something has to be done with the href attribute. Enter the pound sign (#). Unfortunately, because anchor link names are preceded by a pound sign, the browser becomes confused. Not finding a name after the pound, the browser “kicks” the user to the top of the current page, losing the location in the document. The alternative?
javascript:void(0);
There are several explanations regarding the proper use of void, so I won’t go into detail. Basically, a bi-product of its use is that the browser is informed the link goes nowhere, and should therefore, do nothing. For a long time I was happy with this, and never experienced any issues. However, this past year I was working with a software engineer on a Web site where we needed to make heavy use of this technique. I wrapped my link around an image of a checkbox, and called a function to change the source of the image (making it display a checked version of the checkbox). In Internet Explorer, the image disappeared completely. Right-click >> Show Picture — there it is! I spent a half day trying to figure out why, eventually coming across a post on Microsoft’s Web site. It strongly suggested not using javascript:; in the href… ever.
Well, back to the pound sign. After another half day of searching for a solution, I finally came across this bit of code:
<a href="#" onclick="aFunction();return false;"> A Link </a>
The return false (that must appear after the last function call) informs the browser that the action of returning a reference to a URL, should not evaluate. Instead it should return false, including internal links, and therefore it does nothing. I’ve never had an issue since, and any function calls I make evaluate properly.
EDIT: 11/23/06
I have received some comments regarding the functionality in this tutorial. Because my description of the technique does not do it full justice, I am providing a working example. Click here to view the example.
Very valuable experience and it benefits a lot of web developers.
For this specific situation, you could have used an input, type=image also.
-Justin
Hi Justin, you are right, you can use input type=image, and then place the click event directly on that image. Actually, that is another alternative altogether. Instead of wrapping the image in a link if it is just a call to a function, you can always put the onclick directly on the img tag. The only problem with this, is that your cursor does not show the pointer when you roll over it. For this, you would need to change the cursor property.
Thankyou! The first useful article I found to my problem after 10-15 mins of googling.
Lifesaver! Thanks!
Hi Kieran, that is great to hear! Thanks!
Been looking forward to an alternative to void and # for quite sometime. Thanks for the post!
-Peter
Hi Peter, thanks for commenting — glad I could help.
I’ve just had one of the most stressful evenings for a very long time because of void(0).
I tend to use Firefox for my local testing and previewing whilst developing and then test with IE when I’ve got to a milestone. A silly thing to do I guess, but still.
Anyway, everything worked fine in Firefox. In IE that damned image kept disappearing…
Thank you for your (almost!) life-saving article! You star!
Nadeem, glad to hear it! This article appears to be helping a lot of people lately.
Um… but aren’t we back to the real, problem which is that the screen still jumps to the nonexistent # anchor (the top of the screen)?
Yong, if you try the solution, you will see that the screen does not jump to the top. That is the purpose of the “return false” after the final function call.
Hi,
Too good ….i am damn sure hundreds of designers must be huntin for this solution….God bless u.thanx for sharing this info.
viv
Oh man I was going completely crazy with disappearing images in IE. I am sooooooooooooo happy that I found this post, and lucky too, that you included the phrase “show picture” or I don’t know if I would have found it.
I learned a long time ago that it was better to put “javascript:;” than “#” in the href… I hadn’t ever used “javascript:void(0);”
Thanks.. had I not found this post, I don’t know how many more hours I would have wasted altering the actual function my link calls, thinking _it_ was the culprit.
Hey Michael — thanks for the feedback!
I have to agree with Yong Bakos — at least here IE 6 will send me to the top of the page.
Beren (et al.), please see my edit at the bottom of this post.
Wow Thanks!! You just ended a day of painful struggling by providing the magic answer to the question: why are my dynamic images not showing until I right click and chosose Show Picture (a hack that I stumbled upon in another news group posting). Who would have thought that this inocuous javascript:void(0) would cause so much grief. Time for a beer!
Encouraging an excuse for drinking amongst Web developers is my specialty. I’m always happy to hear this solution is still making the rounds. Thanks!
Another useful feature of the #/return false method is that if your JS functions don’t work properly, the return false gets skipped, the page refreshes, and you wind up with “#” in the address bar. Sometimes it’s a handy “flash” of content that will draw your eye to firebug to see what the problem is.
Nice post, Brian!
Hey Rob — thanks for that great bit of info!
[...] Dynamic Pages, Cross-Browser Compatibility You can follow any responses to this entry through the RSS 2.0feed. [...]
Interesting info. I use #null instead of # or void(0). Haven’t got any problem yet.
WORKED LIKE A CHARM! PERFECT!
Good tips, keep posting stuff like this!
What I would like to emphasize is that the onclick/return combo works for every kind of link.
So imagine you really want to show a specifiek size pop-up window with a policy page or something, and you want to make sure everybody sees it (including search engines), you can use something like:
[a href="policy.html" onclick="window.open(this.href,'','width=500,height=300');return false;"]policy[/a]
also, you can simply return false from a function you call, so it can really become a well-thought process, works like a charm in non-intrusive Ajax enabled pages.
( [a href="page2.html" onclick="return followLink(this.href);"]page 2[/a]
Hi Rogier,
Thanks for the comments!
Your point about AJAX is something I have considered editing into this article. If someone needs to meet accessibility requirements regarding JavaScript disabled browsers, then this is a good method. If JavaScript is turned off, you are simply taken to the URL in the href, which doubles as your safeguard purely server-side alternative.
Thanks for helping point that out!
Brian
Thanks for the tip. I was wrangling all over the place with making JavaScript work in an href under Xhtml.
Thanks so much for this little piece of wisdom.
I’ve been using the href void for years without issue until recently creating rounded tabs with CSS and background images. Suddently the tab images were inconsistently disappearing (only for IE) as I navigated through the tabs. The info contained here helped resolved the issue.
It is worth noting that onkeypress=”return false;” did not have the same effect as adding return false to onclick.
Hey Chris, thanks for the additional information about the onkeypress event. Very helpful to know!
Okay, now how would I go about adding two function calls programatically, eg:
newElement.onclick = aFunction;
Where could I put the `return false;` ??
Hi James,
If you don’t want to use the event call within the link itself, then you can add “return false;” to the end of the function. So if you have something like:
newElement.onclick = aFunction;
Your function would look like:
function aFunction() {
… code here …
return false;
}
It only starts to get tricky if your function needs to actually return a value. Hope that helps.
Brian
This article was very helpful for me. Thank you so much for posting this article. I was facing the problem with the links in my web page .
Thanks,
Smitha
Hi Smitha, thanks for the feedback. I’m happy this solution was helpful.
Brian
Your suggestion of “return false” fixed my page so it doesn’t shift to the left. Thanks very much for this great blog.
Thanks Deb — happy to help!
Great blog, very helpful – saved a lot of head scratching (or banging!). I’m Sure I’ll be back with more problems…
and maybe even solve some
Cheers
Hi Brian, I hope you can help me on this problem.. i also have this problem with .. the page is loaded successfully.. the problem that I have is when I place my mouse pointer over the image, the “javascript:void(0)” is displayed on the status bar… but when i removed the mouse pointer from the image, the “Error on page” is displayed… I tried using the href=”#” on the achor tag but still the same… i hope somebody can help me on this… thanks! so sorry if this message is out of place…
Hi Faye,
I think your problem is not actually with the use of JavaScript and void(0), but it is the JavaScript code that is associated with your onmouseout event. I say this only because you are not receiving an error when you mouse over the link. Start by removing any code that you have executing with the onmouseout call, and then work it back in little-by-little. I hope that helps!
Brian
So glad that I found your blog. I have been struggling with the new version of jquery creating issues that the old version didn’t have. Background images would randomly disappear and reappear in ie6 on refresh. On refresh, I executed an onclick event of a hyperlink that had the void in there. Switching to # with return false solved the issue. I always new about using the # method, but I never knew about the consequences of using the void method until today.
Much Thanks!!!
Jeremy Dill
Brilliant! Well done Brian. I’ve always had a ‘natural’ adversion to using ‘void(0)’. However, I’ve been building e-learning sites that have to be DDA compliant (accessibility) and was hitting problems with the screen reader and “<a>” tags (without any images).
But using the return false line and # solved the problem.
Incidenetly, the solution by ibdesign of #null also works.
Nice one!
Thanks Martin! Thanks for letting me know the #null works as well. I wondered but did not get a chance to test it out.
Thank you for the help! 1 day i lost with this problem!!
Does anyone have a link to a demo of why we should not use href=”javascript:;” ? How about the Microsoft post mentioned in this blog entry? I’ve never had a problem using href=”javascript:;” so I want to understand the risks.
Fantastic. Thank you Brian. Very neat blog to read with lots of useful info. One for the Christian Commentary perhaps…watch for the name Javier Solana.
@Jon
Some good “speculation” on Javier’s role in the EU and a one world government. A touchy subject indeed :)
@Joe
I tried, but could not locate the article on MSDN. After I posted the entry, I realized I should have bookmarked the URL. The majority of issues encountered are like the one pointed out in the post, dealing with images not showing up properly. I guess my question would be, what point is there in using anything other than a URL in the href attribute anymore? If you want a good read on accessible JavaScript that discusses why only a URL should appear in the href, give DOM Scripting a browse at the library or bookstore.
Thanks.
Brian
This is too much helpful. Thanks for all the time you invested in finding this solution.
From my experience the use of javascript:void(0) in Safari results in the link and all of it contents being rendered with display:none. I have not found a way around this besides reverting back to the use of #.
Thanks a lot for the tip. We spent sometime trying to figure out why javascript:void(0) wasnt working on IE.. until we came across this article.
Thanks a lot!
I tried the demo that you provided with IE6 on XP/SP2 and the link that should not scroll the browser to the top DOES in fact scroll to the top. (Firefox worked fine) Have there been any recent changes in IE or any settings that would make this technique stop working?
Hi George,
When I first wrote this post, I was running IE 6 on XP/SP2, and did not experience any problems. Since then I have upgraded to IE 7, so it would be difficult for me to test. Are you by chance running a standalone IE 6? Can anyone else test this on IE 6 and tell me if it is working for them?
Brian
If you use the attachEvent/addEventListener methods to attach your events, your solution breaks in FireFox. :-(
Hi Tom -
If you’re using a JavaScript library, or using attachEvent/addEventListener, then you need to remove the “return false” from the link, and attach it to the end of the function call. For intance, in jQuery, it would be:
$(element).onclick(function(){
some code here…
return false;
});
Excellent! Just started running into this problem on a new e-commerce site. Thanks for the solution.
thanks for sharing your experiance… i found it very helpful
Thanks! I spent a couple of hours trying to find a way to do this, and your suggestion was right on.
In my case, I was using JavaScript to initiate a postback after setting a value on the form. For some reason, href=”javascript:void(0);” now breaks / prevents the postback in ie6, but not in ie7 or Firefox. This, of course, was rather frustrating, as the page had been working perfectly for the last year and a half.
The href=”#” was what I needed. The return false; was tasty gravy.
I wonder if you couldn’t also simply use
<a>…</a>
forcing the expression result to a value which will cast to ‘false’ no matter what.
Also, does anyone know how void() is actually implemented in JavaScript (or in a particular browser)? In FF(2.0), it is a syntax error to ask what
typeof void
is, though
typeof void(0)
comes back as ‘undefined’, reasonably enough.
Is void not really a ‘function’-typed thing in JavaScript? It seems to be a keyword, that acts like a function… but you can’t call
void()
either..
I’m confused.
@Bryan
That is a very interesting point. According to the W3C, your document should still validate if you leave off the attributes for the anchor element. It would be worth testing if that works. However, one thing to consider with that method is that you lose SEO. Typically, you should have some URL in the href, even if you return false. That way you can execute a script, but search engines can still follow a URL to a destination.
Brian
I don’t know why, but your demo isn’t working on my IE7 (WinXP, SP2), the href is executed in both links. The thing that works for me is: <a href=”;” rel=”nofollow”>
I’m sorry to hear you are having problems. I am on Windows XP (SP2), and I use IE 7, and I have not had any issues.
[...] reference: d’bug [...]
[...] The biggest challenge was making it compatible with IE6. First, IE6 did not support innerHTML very well so I had to create all objects via the DOM interface. Lot of work! Another tricky bug was the void(0) issue which interrupts the requests to the servers…. [...]
[...] I don’t see this ever happening. Not when even supposedly web-savvy companies like Google use javascript:void(0) on their personalized home [...]
[...] Related Reading: An anecdote about not using href=“javascript: void(0);” [...]
[...] link is replying to whose comment. Also this is a bad approach to screen reader. Consider we should avoid the javascript:void(0) [...]
[...] August 10, 2009 I do a lot of onClick events and I hate the pound. I never had the interest to really evaluate this further, but I figured while waiting for code to compile I would do some research. First what works for client side execution and what are the issues <a href="#" onClick="javascript: alert(’Hello Wold’)">Click Me</a> This option is to use the pound in the href to make the browser think that it is a bookmark. In turn after the link is executed the OnClick event is fired causing the alert window. Works great until you have a long page and suddenly the page scrolls to the top, not what you wanted. <a href="javascript: alert(’Hello World’)">Click Me</a> This option is to use javascript in the href attribute. This will only work in IE. <a href="javascript: alert(’Hello Word’)" onClick="javascript: alert(’Hello Word’)">Click Me</a> This option is to use the javascript in both the href and onclick attributes. This will work for all browsers however, duplicating code like this can be annoying. <a href="#" onClick="javascript: alert(’Hello World’); return false;">Click Me</a> This option is to use the href and the onclick attributes however in the onClick event, tell the browser to disregard the click. This technique goes back to the ability to stop a form from submitting after you click the submit button. This will remove the issue seen in option 1. The following link shows this same setup. http://blog.reindel.com/2006/08/11/a-hrefjavascriptvoid0-avoid-the-void/ [...]