Jump to content

general javascript question


anujgarg

Recommended Posts

we call a javascript function by two ways-

 

actually there are more ways such as placing an event listener. This is one i prefer  because you dont have to browse through all the html to find what link has what function.

 

 

 

<a href='javascript:fnName(id)'>ABC</a>

when javascript is disabled nothing will happen

and

 

 

<a href='a_link.html' onclick='fnName(id)'>ABC</a>

 

What is the difference between these two? Also, which one is fast?

when javascript is disabled now it will go to a_link.html

 

The first version of the link uses what is called a pseudo-protocol to invoke the JavaScript.  http:// and ftp:// are real protocols.  javascript: is meant to be used within the href attribute of a link, much like those protocols.  Like Dj Kat said above, if JavaScript is turned off, then any link using the pseudo-protocol will be broken.

 

The second version uses an inline event handler.  Again, like Dj Kat said, if JavaScript is disabled, the URL in the href attribute will be followed.

 

I don't know if one is faster than the other.  The second option is the best of those two choices.  I prefer to not use inline event handlers, though, because it couples site structure (the HTML) to site behavior (the JavaScript).  Instead, I code unobtrusively, like so:

 

<html>
<head>
   <title>Blah</title>
   <script type="text/javascript">
      window.onload = function()
      {
         var myLink = document.getElementById('myLink');
         myLink.onclick = someFunction;

         function someFunction()
         {
            alert("My id is: " + this.id);
            return false; //make sure the link IS NOT FOLLOWED
         }
      }
   </script>
</head>

<body>
   <a href="http://www.google.com" id="myLink">Clicky</a>
</body>

</html>

 

Same functionality, but editing, maintaining, and debugging the JavaScript just got a whole lot easier as it's all in one centralized location, and not sprinkled throughout the HTML.  The code, with very little modification (remove window.onload = function() { }), could even be placed in an external file, usable by the entire site, much like external CSS files.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.