Computers & ProgrammingFrontend DevelopmentJavaScript

JavaScript Void(0) Function

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>

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>

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>

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.

Leave a Comment

Your email address will not be published.

Scroll to Top