4

I have this code:

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

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

</body>
</html>

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

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

my code runs normally.

Is that a difference between onclick="javascript:myFunction()" and onclick="myFunction()" ?

Serenity
  • 32,301
  • 18
  • 107
  • 109
senior
  • 2,066
  • 6
  • 34
  • 53

1 Answers1

7

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.

Guffa
  • 666,277
  • 106
  • 705
  • 986