Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()" ?

like image 229
senior Avatar asked Mar 19 '23 14:03

senior


1 Answers

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.

like image 70
Guffa Avatar answered Apr 06 '23 14:04

Guffa