According to the definition, void denotes "totally empty space." When used in programming, this term refers to a return of "nothing" - or, to put it another way, a "empty value."
When an expression is evaluated using the void operator, the result is undefined. This operator is typically used to obtain an undefined primitive value. It's frequently used in conjunction with hyperlinks. When you click a link, your browser usually refreshes the page or loads a new one. When we don't want the browser to refresh or load a new page when we click a hyperlink, we can use javascript:void(0).
The operand 0 can be used in two ways: void(0) or void 0. Both methods are equally effective. JavaScript:void(0) instructs the browser to "do nothing," preventing the page from being reloaded or refreshed. It's useful when we want to insert links that are vital to the webpage without having to reload the page. Using void(0) on such links stops the page from reloading but allows a useful function like updating a value on the webpage to be performed.
<!DOCTYPE html> <html> <head> <title>Understanding JavaScript void(0)</title> </head> <body> <a href="javascript:void(0);" ondblclick="alert('Click it twice!')">Click me not once, but twice.</a> </body> </html>
To prevent the website from reloading when the button is pressed for the first time, we utilised JavaScript: void(0).
The code will only operate if the button is clicked twice, as illustrated above. Nothing occurs if you only click it once. However, because we utilised the ondblclick
event handler, the alert box appears when the button is pressed twice.
The use of JavaScript:Void(0) to keep the website from refreshing is a quick and straightforward approach, but it's not the most scalable or accessible, and it violates the rules of unobtrusive JavaScript.
It's typically preferable to use a separate HTML element as the JavaScript trigger (for example, a button> element). If you want it to look more like a hyperlink, you can use CSS to adjust its appearance.
🚀 As an alternative to JavaScript:void, you can use event.preventDefault with the event handler (0). Here's an illustration:
<!DOCTYPE html> <html> <head> <title>JavaScript void 0 alternatives</title> </head> <body align="center"> <h2>Using .preventDefault()</h2> <a href="https://www.logicmojo.com" onclick="event.preventDefault();" ondblclick="alert('Task completed')">Double Click Me!</a> </body> </html>
🚀 Return false is another option to JavaScript void 0. The browser will not take any action if the click returns false.
<!DOCTYPE html> <html> <head> <title>JavaScript void 0 alternatives</title> </head> <body align="center"> <h2>Using return false()</h2> <a href="https://www.logicmojo.com" onclick="return false;" ondblclick="alert('Task completed')">Double Click Me!</a> </body> </html>
Conclusion: At this point, you should have a better understanding of JavaScript Void(0). When a page is clicked, it will not navigate to another page or reload the current page.