views:

120

answers:

3

Hello, I would like to know what is the difference between javascript:; and javascript:void(0); if I use them in href attribure for a anchor (link)

<a href="javascript:;" onclick="DoSomething();">Link</a>

<a href="javascript:void(0);" onclick="DoSomething();">Link</a>

I see them acting the same on all browsers but what is the technical difference?

Regards, Magdy

+5  A: 

One runs JavaScript that has no statements, the other runs JavaScript that evaluates the statement 0 and then returns undefined.

Neither should be used.

David Dorward
+1 for discouraging this pattern. Being really pedantic, actually the first contains *one* statement, the [Empty Statement](http://bclary.com/2004/11/07/#a-12.3) `;` :P
CMS
+1, also for discouragement of this pattern.
Tim Down
+3  A: 

Only that the latter javascript:void(0); is more readable and an accepted convention that says this code does nothing.

It's worth noting that industry standards have come a long way regarding this syntax. You should look into Progressive Enhancement.

Jason McCreary
+4  A: 

I agree with David that neither should be used. The javascript pseudo-protocol can put the page into a waiting state in some browsers, which can have unexpected consequences. As one example, I spent hours trying to debug a web app that was crashing IE6 whenever someone clicked a javascript: link soon after the page loaded. It turned out that the page entering the waiting state was conflicting with a Flash movie trying to initialize. I solved the problem by replacing the link with one in this format:

<a href="#" onclick="DoSomething(); return false;">Link</a>

The "return false" prevents the link from actually being followed.

Rob Cooney
So if JavaScript is available it will `DoSomething` and if it isn't … it links to the top of the page. That is almost always going to be an awful fallback position.
David Dorward