I have seem some people put their code inside of the void function. I have also seen this in hrefs: javascript:void(0) which doesnt seem any better than writing javascript:;
so, what is the justification of using the void function?
I have seem some people put their code inside of the void function. I have also seen this in hrefs: javascript:void(0) which doesnt seem any better than writing javascript:;
so, what is the justification of using the void function?
Explanation of its use in links:
<snip>
This is the reason that bookmarklets often wrap the code inside void() or an anonymous function that doesn't return anything to stop the browser from trying to display the result of executing the bookmarklet. For example:
javascript:void(window.open("dom_spy.html"))
If you directly use code that returns something (a new window instance in this case), the browser will end up displaying that:
javascript:window.open("dom_spy.html");
In Firefox the above will display:
[object Window]
</snip>
Consider the following:
<a href="javascript:void(fish=document.getElementById('foo').value);void(document.getElementById('bar').value=fish);">With Void</a>
<a href="javascript:fish=document.getElementById('foo').value;document.getElementById('bar').value=fish;">Without Void</a>
<input type="text" id="foo" value="one fish" />
<input type="text" id="bar" value="no fish" />
The first link with swap the values of the text fields. The second link will open a new page with the text "one fish". If you use a javascript: link
, the minute an expression returns something other than null
or undefined
, the browser will interpret that as what the link should do. By wrapping all expressions/statments in a void()
function, you ensure your entire snippet of code will run. These days, this is primarily of use in Bookmarklets, as using an onclick
attribute, or setting up event handlers in separate Javascript blocks/files is the "norm".
As for javascript:
vs. javascript:void()
, the first statement is ambiguous. You're saying, "hey, I want to run some javascript", but then you don't provide any code. It's not necessarily clear what the browser should do here. With the second statement you're saying "hey, run some javascript", and your code eventually returns undefined, which the browser knows means "do nothing".
Since I'm here, I'll also point out that using either javascript:
or javascript:void();
has fallen out of favor with most people who care about markup. The better thing to do is have your onclick handler return false, and have the link pointed towards a page/resource that makes sense for people who have javascript turned off, or are using a javascript blocker such as NoScript.