JavaScript Void(0)

Sometimes, you may need to call some JavaSript from within a link. Normally, when you click a link, the browser loads a new page (or refreshes the same page).

This might not always be desirable. For example, you might only want to dynamically update a form field when the user clicks a link.

To prevent the load from refreshing, you could use the JavaScript void() function and pass a parameter of 0 (zero).

Example of void(0):

We have a link that should only do something (i.e. display a message) upon two clicks (i.e. a double click). If you click once, nothing should happen. We can specify the double click code by using JavaScript's ondblclick method. To prevent the page reloading upon a single click, we can use JavaScript:void(0); within the anchor link.

CodeResult

Double Click Me!

Same Example, but without void(0):

Look at what would happen if we didn't use "JavaScript:void(0);" within the anchor link...

CodeResult

Double Click Me!

Did you notice the page refreshed (or loaded another page) as soon you clicked the link. Even if you double clicked and triggered the ondbclick event, the page still reloads!

If the website uses a <base> element, the link will lead to the URL specified in the <base> element. Either way, JavaScript's "void()" method will prevent this from happening.

The void(0) method can become useful when you need to call another function that may have otherwise resulted in an unwanted page refresh.

Enjoy this page?