What Does JavaScript Void(0) Mean?
The JavaScript void
operator evaluates the given expression and then returns a value of undefined
.
You may ocassionally encounter an HTML document that uses href="JavaScript:Void(0);"
within an <a>
element.
JavaScript void
is often used when, inserting an expression into a web page may produce an unwanted side-effect.
By using JavaScript:Void(0)
, you can eliminate the unwanted side-effect, because it will return the undefined
primative value.
A common usage of JavaScript:Void(0)
is with hyperlinks.
Sometimes, you may need to call some JavaScript from within a link. Normally, when you click a link, the browser loads a new page or refreshes the same page (depending on the URL specified). But you probably don't want this to happen if you've attached some JavaScript to that link.
To prevent the page from refreshing, you could use JavaScript:void(0)
.
Example of JavaScript:void(0)
We have a link that should only do something (display a message) upon two clicks (a double click). If you click once, nothing should happen. We can specify the double click code by using the ondblclick
event handler. To prevent the page reloading upon a single click, we can use JavaScript:void(0);
within the anchor link.
Same Example, but without JavaScript:void(0)
Look at what would happen if we didn't use JavaScript:void(0);
within the anchor link...
Did you notice the page refreshed as soon you clicked the link (actually, it refreshed the <iframe>
content on this example — therefore, the above link probably disappeared when you clicked it). Even if you double clicked and triggered the ondbclick
event, it will still happen!
So the void
operator can be useful when you need to call another function that may have otherwise resulted in an unwanted page refresh.
If the website uses a <base>
element, the link will lead to the URL specified in the <base>
element. Either way, using void(0)
will prevent this from happening.
JavaScript:Void(0) Alternatives
The practice of using JavaScript:Void(0)
to prevent the page from refreshing is a quick and easy solution, but not necessarily the most scalable or accessible solution, and it doesn't follow the principles of unobtrusive JavaScript.
It's often better to use a different HTML element as the trigger for the JavaScript (a <button>
element for example). You can use CSS to change its appearance if it needs to look more like a hyperlink.
However, if you must use the <a>
element, try to ensure that the href
attribute uses a valid URL so that non-JavaScript users can still reach the content in some way.
event.preventDefault()
When doing this, you can use event.preventDefault()
within an onclick
event handler to prevent the page from refreshing.
return false
Using return false;
will do the same thing.