Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you ever need to specify 'javascript:' in an onclick?

AFAIK, you never need to specify the protocol in an onclick:

onclick="javascript:myFunction()" Bad

onclick="myFunction()" Good

Today I noticed in this article on Google Anallytics that they are using it:

<a href="http://www.example.com" onClick="javascript: pageTracker._trackPageview('/outgoing/example.com');"> 

Is this example just plain wrong, or is there ever a reason to specify javascript: in anything other than a href?

like image 434
Diodeus - James MacFarlane Avatar asked Dec 16 '08 18:12

Diodeus - James MacFarlane


People also ask

How Onclick works in JavaScript?

The onclick event generally occurs when the user clicks on an element. It allows the programmer to execute a JavaScript's function when an element gets clicked. This event can be used for validating a form, warning messages and many more. Using JavaScript, this event can be dynamically added to any element.

Does Onclick work with all elements?

HTML DOM onclick event supports All HTML elements, EXCEPT: <base> <bdo> <br>

Is onclick JavaScript or HTML?

Note that the onclick attribute is purely JavaScript. The value it takes, which is the function you want to execute, says it all, as it is invoked right within the opening tag. In JavaScript, you invoke a function by calling its name, then you put a parenthesis after the function identifier (the name).


2 Answers

Some of the responses here claim that the "javascript:" prefix is a "leftover from the old days", implying that it's intentionally, specially handled by the browsers for backwards compatibility. Is there solid evidence that this is the case (has anyone checked source code)?

<span onclick="javascript:alert(42)">Test</span> 

To me, this just reads as:

javascript:     alert(42); 

Meaning, that "javascript:" is just a label and has no effect. This works, too:

<span onclick="foobar:alert(42)">Test</span> 

Update:

I did a little experiment and it turns out that, yes, "javascript:" is handled specially by IE, but definitely not so by Firefox, Safari, Opera or Chrome:

<span onclick="javascript:while (true) { alert('once'); break javascript; }">Test</span> 

On non-IE, this will just alert "once", once and then break out of the loop. On IE, I get a "Label not found" error. The following works fine in all browsers:

<span onclick="foo:while (true) { alert('once'); break foo; }">Test</span> 

Update 2:

I just realized the link http://crisp.tweakblogs.net/blog/the-useless-javascript-pseudo-protocol.html in one of the answers above pretty much talks about the same thing.

like image 186
Ates Goral Avatar answered Oct 02 '22 06:10

Ates Goral


It's never needed on anchors and is never good practice. An anchor is for navigation only. An article about this topic is The useless JavaScript: pseudo-protocol.

like image 39
I.devries Avatar answered Oct 02 '22 05:10

I.devries