The void operator is used to evaluate an expression and returns the undefined. Generally, this operator is used for obtaining the undefined primitive value. It is often used with hyperlinks. Usually the browser refreshes the page or loads a new page on clicking a link. The javascript:void(0) can be used when we don’t want to refresh or load a new page in the browser on clicking a hyperlink.
We can use the operand 0 in two ways that are void(0) or void 0. Both of the ways work the same. The JavaScript:void(0) tells the browser to “do nothing” i.e., prevents the browser from reloading or refreshing the page. It is useful when we insert links that have some important role on the webpage without any reloading. So, using void(0) on such links prevents the reloading of the page but allows to perform a useful function such as updating a value on the webpage.
It is also used to prevent unwanted redirecting of the page.
Syntax
expression
Let’s understand the use of javascript:void(0); using some examples.
Example1
In the following example, we are defining two links. In the first link, we are using the void keyword. When the corresponding link gets clicked, it will do nothing because of the void(0).
When we click on the second link, it will display an alert dialog box.
<html>
<head>
</head>
<body>
<center>
<h1> Hello World :) :) </h1>
<h2> Click the following links to see the changes </h2>
<h4> It is an example of using the <i> javascript:void(0); </i> </h4>
<a href = "javascript:void(0);">
It will do nothing.
</a>
<br/><br/>
<a href = "javascript:alert('Welcome to javaTpoint');"> Click here for an alert </a>
</center>
</body>
</html>
Output
On clicking the first link, nothing will happen. When the user clicks the second link, the output will be –
Now, in the next example, we will see how to prevent redirecting of the webpage.
Example2
In this example, we are passing the javascript:void(0); and link of the website to the href attribute. Here, we are also using the ondblclick attribute, which shows an alert box on double-clicking the hyperlink. On closing the alert dialog box, the page will not redirect to the specified link of the website.
<html>
<head>
<style>
a{
font-size: 22px;
}
</style>
</head>
<body>
<center>
<h1> Hello World :) :) </h1>
<h2> Click the following link to see the changes </h2>
<h4> You can see on closing the alert dialog box, the page will not redirect to https://www.javatpoint.com/ </h4>
<a href = "javascript:void(0);https://www.javatpoint.com/" ondblclick = "alert('Welcome to the javaTpoint.com')">
Double click the link
</a>
</center>
</body>
</html>
Output
On double-clicking the specified link, the output will be –
Leave a Reply