Why use javascript:void(0) in hyperlinks?

By Faruque Ahamed Mollick

We often may have to use javascript:void(0) in our hyperlink. So in this post, I am going to tell you why we use javascript:void(0) the href attribute of our anchor tag or hyperlink.

Below is an example of using javascript:void(0) in hyperlinks:

<a href="JavaScript:void(0);">Click Me!</a>

If we test the above code in the browser, we can see nothing happened. Normally if we left the href attribute value blank, it will refresh the page. So we can see that JavaScript void preventing us from refreshing the page as we can see nothing happen when we use it in our href attribute.



Now the question can come. If nothing happened on clicking the hyperlink, then why we use it?

Before I am going to tell you why we use it, let’s see a real example of using javascript:void(0) below:

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

In the above code, we can see that we run our simple JavaScript code when user click on the hyperlink. But we have to prevent our page from refreshing. So here we have used the JavaScript void(0) to prevent our page from refreshing.

Generally, in practical work, we pass JavaScript  function as we can see below:

<a href="JavaScript:void(0);" onclick="my_function();">Click Me!</a>

And then, our JavaScript code:

<script>
    function my_function() {
          alert("Hyperlink clicked");
    }
</script>

Here we have created our JavaScript function and then call it in our hyperlink using the attribute. This is the real usage of javascript:void(0) of calling a JavaScript function with a hyperlink.

Also, we can apply onclick without using it in hyperlink attribute. We can take an ID for the anchor tag and apply click event listener to the ID.

So the main purpost of using JavaScript void(0) is to prevent the hyperlink from refreshing the page or from sending any other page.

Well we can also prevent refreshing page using “#” as the value to the href attribute:

<a href=”#”>Click Me!</a>

But it will send us to the top of the page.

Although, there are the alternative methods available to the javascript:void(0), here we only focused on using  javascript:void(0).

 

Also, read:

 

I hope, this post helps you to understand the usage of javascript:void(0) in hyperlinks.

Leave a Reply

Your email address will not be published. Required fields are marked *