onclick="javascript:alert('a')" vs. onclick="alert('a')"

Hi All,

Are there any benefits to doing :
onclick=“javascript:alert(‘a’)” vs. onclick=“alert(‘a’)”

Secondly, how do I search for this on the net? I’m not able to come up with search terms that generate any good results.

As the content of the onclick is already JavaScript the javascript: is interpreted as a JavaScript label that isn’t referenced from anywhere and so is completely superfluous. You only need labels in JavaScript where you have a switch statement or where you havenested loops and want to be able to break or continue out of more than one level at the same time.

for example you need labels in:

switch(lang) {
   case javascript: js(); break;
   case php: php(); break;
   default: unknownlang();
}

or in:

double: for (i = 0; i < l1; i++) {
    for (j = 0; j < l2; j++) {
        do_something();
        if (test_finished()) break double;
    }
}

but nowhere else do labels in JavaScript actually get used

Thanks felgall! Your answer was to the point and helpful.

I don’t think it has anything to do with a label at all.

It’s called a protocol, as in the first part of a URL, like ‘http:’ or ‘mailto:’. The syntax probably comes from the fact that you can write code like this

<a href=“javascript:alert(‘a’);return false;”>Click Here</a>

It really has no meaning if you change href to onclick. But I have seen some old Microsoft (Internet Explorer) pages with mixed VBScript and JavaScript. In this case, I think you could have used the protocol to call a VBScript function, as in onclick = ‘vbscript:MsgBox(“a”)’. Don’t think this works in current browsers though.

To search for it on the internet, try “HTML javascript protocol”. When I ran this search in Google, there was a good article from Stack Overflow (5th result).

http://stackoverflow.com/questions/2479557/why-is-it-bad-practice-to-use-links-with-the-javascript-protocol