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
  • 35,289
  • 20
  • 120
  • 115
senior
  • 2,196
  • 6
  • 36
  • 54

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
  • 687,336
  • 108
  • 737
  • 1,005