Why use `javascript:void(0)` instead of `javascript:` as an href do nothing placeholder?

Bryan Field picture Bryan Field · Mar 8, 2011 · Viewed 23.6k times · Source

I have seen href="javascript:void(0)" and I have seen href="javascript:;" Is there any reason I would not just use href="javascript:" instead?

Edit: Let me make it clear: I am combining this with an onclick and have no objection to using return false if it becomes necessary to use the alternative. Of course this is only if the alternative makes better sense over javascript:.

Also, I have yet to see a answer to my question shown (clearly I think) in the first paragraph. Thanks, david. :)

I have seen href="javascript:void(0)" and I have seen href="javascript:;" Is there any reason I would not just use href="javascript:" instead?

Answer

Spudley picture Spudley · Mar 8, 2011

Personally I'd avoid using either. I'd have onclick='return false;' instead, and just set href='#'.

Why? Because if you put Javascript code in the href, then it appears in the browser's status bar when you hover over the link, just like any other URL. It just looks messy.

In fact, since it's going to be ignored anyway, you could put any URL you fancy into the href, not just a hash. The hash is safest, just in case your user has Javascript disabled, but aside from that point, it could be anything.

But I have to point out: having an <a> tag with the href going to a void Javascript code seems to rather defeat the point of having an <a> tag in the first place. I can see how you'd want to enable and disable a link at runtime, but simply setting the href to void does seem somewhat pointless. If it isn't going to be a real link, why not just have a <span> or some other tag. If you must make it look like a link, it's trivial to do that in CSS.