JavaScript Void(0) Function

Thursday, May 03, 2012

Using hyperlinks in combination with JavaScript is a very useful way of performing certain actions on the web page. For example, you may want to update some content on your page without requiring the page to reload. A post-back adds additional delays and processing power on your webserver. This may not always be desirable or even necessary.

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


void(0)

In the following example, we will use an anchor link (hyperlink) and set the "href" attribute to "javascript:void(0)". We will also use the "ondblclick" method just so you can actually see the results of clicking once versus clicking twice.


<a href="JavaScript:void(0);" 
    ondblclick="alert('You clicked twice!')">
        Double Click Me!</a>


Results


Double Click Me!


Let us take a look at the same example without the use of the JavaScript void(0) function.


<a href="" 
    ondblclick="alert('You clicked twice!')">
        Double Click Me!</a>


Results


Double Click Me!


You should have noticed that regardless if you clicked on the link once or twice, the page was reloaded. Here is another example where we can use a hyperlink to update the value of a textbox.


<script type="text/javascript">
  function updateText(x) {
    document.getElementById('txtBox1').value = x
    }
</script>

<input id="txtBox1" type="text" /><br /><br />
<a href="JavaScript:void(0);
  updateText('Hello!');">Click Me!</a>


Results





Click Me!


These were just some simple examples. As you can now imagine, this technique can be very useful when you want to call another function without reloading the page. This technique helps greatly improve your visitors' experience while on your website.

Did you find the page informational and useful? Share it using one of your favorite social sites.

Recommended Books & Training Resources

JavaScript and jQuery: The Missing Manual HTML CSS and JavaScript Editor Murachs JavaScript and DOM Scripting