Using the void operator in anchor links

Jake Howlett, 16 October 2000

Category: JavaScript; Keywords: Return window confirm

Have you noticed that if you create a URL that calls a JavaScript function or method, in which an object gets returned but the browser is not told what to do afterwards, the browser will then do something like this:

Image

For example, click on the following pseudo-URL (remember - use the back button to return here) :

JavaScript:window.open('/icons/vwicn012.gif', 'test', 'width=200,height=200');

This happens becuase the browser thinks it should open the JavaScript as an explicit URL. Did you notice that the address box of the browser changed?

Placing the void operator in front of the JavaScript call will solve this. The void unary operator tells the browser to evaluate the following expression but ignore the value it returns.

Try it now by clicking on the link below:

JavaScript:void window.open('/icons/vwicn012.gif', 'test', 'width=200,height=200');

The browser no longer misbehaves when you open the window.

On an aside, there is another way around this. You can place the url call in to the anchor tag using the onClick event and having a href attribute that points nowhere.

<a href="#" onClick="window.open('/icons/vwicn012.gif', 'test', 'width=200,height=200');">I don't like this method</a>


But I would consider this more of a "workaround" than a solution.

As a rule I always tend to include it whenever I place JavaScript inside the href of a link. Better safe than sorry. Unless, of course, you expect the link to be the returned object from the JavaScript call.