How to use a link to call JavaScript?

ID : 20341

viewed : 8

Tags : javascriptjavascript

Top 5 Answer for How to use a link to call JavaScript?

vote vote


Unobtrusive JavaScript, no library dependency:

<html> <head>     <script type="text/javascript">          // Wait for the page to load first         window.onload = function() {            //Get a reference to the link on the page           // with an id of "mylink"           var a = document.getElementById("mylink");            //Set code to run when the link is clicked           // by assigning a function to "onclick"           a.onclick = function() {              // Your code here...              //If you don't want the link to actually              // redirect the browser to another page,             // "" in our example here, then             // return false at the end of this block.             // Note that this also prevents event bubbling,             // which is probably what we want here, but won't              // always be the case.             return false;           }         }     </script> </head> <body>     <a id="mylink" href="">linky</a>         </body> </html> 
vote vote


<a onclick="jsfunction()" href="#"> 


<a onclick="jsfunction()" href="javascript:void(0);"> 


The above response is really not a good solution, having learned a lot about JS since I initially posted. See EndangeredMassa's answer below for the better approach to solving this problem.

vote vote


<a href="javascript:alert('Hello!');">Clicky</a> 

EDIT, years later: NO! Don't ever do this! I was young and stupid!

Edit, again: A couple people have asked why you shouldn't do this. There's a couple reasons:

  1. Presentation: HTML should focus on presentation. Putting JS in an HREF means that your HTML is now, kinda, dealing with business logic.

  2. Security: Javascript in your HTML like that violates Content Security Policy (CSP). Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks. These attacks are used for everything from data theft to site defacement or distribution of malware. Read more here.

  3. Accessibility: Anchor tags are for linking to other documents/pages/resources. If your link doesn't go anywhere, it should be a button. This makes it a lot easier for screen readers, braille terminals, etc, to determine what's going on, and give visually impaired users useful information.

vote vote


And, why not unobtrusive with jQuery:

  $(function() {     $("#unobtrusive").click(function(e) {       e.preventDefault(); // if desired...       // other methods to call...     });   }); 


<a id="unobtrusive" href="">jquery</a> 
vote vote


Unobtrusive Javascript has many many advantages, here are the steps it takes and why it's good to use.

  1. the link loads as normal:

    <a id="DaLink" href="http://host/toAnewPage.html">click here</a>

this is important becuase it will work for browsers with javascript not enabled, or if there is an error in the javascript code that doesn't work.

  1. javascript runs on page load:

     window.onload = function(){         document.getElementById("DaLink").onclick = function(){                if(funcitonToCall()){                    // most important step in this whole process                    return false;                }         }  } 
  2. if the javascript runs successfully, maybe loading the content in the current page with javascript, the return false cancels the link firing. in other words putting return false has the effect of disabling the link if the javascript ran successfully. While allowing it to run if the javascript does not, making a nice backup so your content gets displayed either way, for search engines and if your code breaks, or is viewed on an non-javascript system.

best book on the subject is "Dom Scription" by Jeremy Keith

Top 3 video Explaining How to use a link to call JavaScript?