view raw
junior junior - 11 months ago 31
HTML Question

Why do we add "javascript:" before calling a function in HTML?

I have this code:

function myFunction() {
document.getElementById("demo").innerHTML="Hello World";
<button onclick="javascript:myFunction()">Click me</button>

<p id="demo"></p>


if I change
<button onclick="javascript:myFunction()">Click me</button>

<button onclick="myFunction()">Click me</button>

my code runs normally.

Is that a difference between


That's the javascript: pseudo-protocol, that has got lost. It's used when you have Javascript in an URL, for example:

<a href="javascript:alert('hi')">Hi</a>

An event attribute doesn't support the :javascript protocol, so it doesn't work there. However, it happens to become the same syntax as a label in Javascript, so the code actually still works eventhough the protocol is in the wrong place.

So, in conclusion, the :javascript shouldn't be there, and it's just plain luck that it still happens to work when it is.