Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is javascript:void(0) considered harmful?

Tags:

javascript

Can anybody tell me or point me to some resource which explains why using javascript:void(0) in hyperlinks is harmful (especially in Internet Explorer 6)?

like image 581
Abhi Avatar asked Feb 15 '10 09:02

Abhi


1 Answers

Use of the javascript: keyword in a link isn't recommended anyway. I've only managed to find one article on why it might be harmful:

a href=”javascript:void(0);” — avoid the void

But the general consensus shows that you shouldn't use it because it might confuse browsers without javascript support, for some of those browsers it could be parsed as an invalid link.

Instead, you should provide a link to a page either working around the functionality that would be provided by javascript or displaying a message about the site requiring javascript to work correctly. On the same link, return false; from your event, like so:

<a href="noscript.html" onclick="doSomething(); return false;">I'm a link</a>

Or alternatively, use return false; or preventDefault() and returnValue in your javascript code:

element.onclick = function ()
{
    /*
        // return false is better for most situations (see bobince's comment)
        if (event.preventDefault)
            event.preventDefault();
        else
            event.returnValue = false;
    */

    doSomething();

    return false;
}
like image 51
Andy E Avatar answered Sep 29 '22 10:09

Andy E