Recent Articles

The Infamous JavaScript void() Function

Once in a while, I have a need to use a HTML hyperlink to perform client-side behavior like open a new window, modify a field or any imaginable DHTML task. There's actually a few ways to accomplish that and prevent the hyperlink from firing a web navigation to another page. Some people prefer to use a static anchor (#) for the href and specify and onclick event.

 <a href="#" onclick="'page.html', '', '')" >Visit me</a>

Another way is to return a false value in the onclick event and use an inline javascript on the href:

  <a href="'page.html', '', '')" onclick="return false" >Visit me</a>

I personally prefer to keep everything on the href. The problem with this approach is that the browser will still navigate away because the function returns a handle to the newly created window and the hyperlink thinks that's the URL being passed in. A little infamous function called void(0) takes care of the problem by silencing the event.

 <a href="javascript:void('page.html', '', ''))" >Visit me</a>

The void(0) function actually returns null and works wonderfully by cancelling the page load. Older browsers do not recognize the void(0) function. As such, you might see people implement the void(0) function themselves.

function void(obj) { return null; }

So be sure to test different browsers before using it and have fun!