Tuesday, 2 September 2014

Calling JavaScript function in href vs. onclick

Background

There are multiple ways to call a Javscript function in an anchor tag. You can put the method in href attribute or you can use onclick event or jquery events. This post is about good practices while calling a javascript function in such a scenario.


Usage in order of  increasing good practice


<a id="myLink" href="javascript:MyFunction();">link text</a>
 
<a id="myLink" href="#" onclick="MyFunction();">link text</a>
 
<a id="myLink" href="#" onclick="MyFunction();return false;">link text</a>
 
<a id="myLink" title="Click to do something" href="#" onclick="MyFunction();return false;">link text</a>
 
<a id="myLink" title="Click to do something" href="PleaseEnableJavascript.html" onclick="MyFunction();return false;">link text</a>

But the best practice as of now is to use jquery and attach an even handler to the elements id. Something like -

$('#myLink').click(function()

  {

     MyFunction();

     return false;

  }); 

 Notes

  • The onclick won't fire if someone middle-clicks on your link to open a new tab or if they have JavaScript disabled.
  • In case javascript is enabled adding return false in  onclick will will prevent browser from following the link.
  •  If you don't have a link in href attribute you should do javascript:void(0) rather than # in the href attribute.  '#' will take the user back to the top of the page if it is present in the href attribute and onclick is not returning false.

 

Related Links


No comments:

Post a comment

t> UA-39527780-1 back to top