Computer >> Computer tutorials >  >> Programming >> Javascript

JavaScript function in href vs. onClick


Both onclick & href have different behaviors when calling JavaScript directly. Also the script in href won’t get executed if the time difference is short. This is for the time between two clicks.

Example

Here’s an example showing the usage of href vs onClick in JavaScript.

<html>
   <head>
      <title>JavaScript href vs onClick()</title>
      <script>
       function myFunc() {
         var v = 0;
         for (var j=0; j<1000; j++) {
            v+=j;
         }
         alert(v);
      }
      </script>
      <a href="javascript:myFunc()">href</a>
      <a href="#" onclick="javascript:myFunc()">onclick</a>
      </head>
   <body>
   </body>
</html>