What does "javascript:void(0)" mean?

What does "javascript:void(0)" mean?

As a web developer, I have come across the term "javascript:void(0)" in my code, and it can be confusing to understand its purpose.

Essentially, "javascript:void(0)" is a JavaScript code that is used to prevent the default action of an HTML link from executing. When you click on a link, by default, the browser navigates to the URL specified in the link's href attribute. However, sometimes, you want to perform some JavaScript code instead of navigating to a new page.

In such cases, you can use "javascript:void(0)" as the value of the href attribute of the link. This tells the browser to execute the JavaScript code specified in an onclick event or in the link's href attribute itself. It effectively prevents the browser from navigating to a new page.

Example Usage:


      <a href="javascript:void(0)" onclick="alert('Hello World!')">Click Me</a>
    

In the above example, when you click on the link, instead of navigating to a new page, it will execute the JavaScript code specified in the onclick attribute, which will show an alert box with the text "Hello World!"

Another common use case for "javascript:void(0)" is when you want to create a link that performs some JavaScript code and then redirects the user to a new page. In such cases, you can use "javascript:void(0)" as the value of the href attribute and then use window.location.href to redirect the user after performing some JavaScript code.

Example Usage:


      <a href="javascript:void(0)" onclick="doSomething(); window.location.href='http://example.com';">Click Me</a>
    

In the above example, when you click on the link, it will execute the doSomething() function and then redirect the user to http://example.com.

Overall, "javascript:void(0)" is a useful code snippet that can help you manipulate the default behavior of links in HTML pages.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe