Skip to main content

JavaScript function in href vs. onclick



bad:
 id="myLink" href="javascript:MyFunction();">link text
good:
 id="myLink" href="#" onclick="MyFunction();">link text
better:
 id="myLink" href="#" onclick="MyFunction();return false;">link text
even better 1:
 id="myLink" title="Click to do something" href="#" onclick="MyFunction();return false;">link text
even better 2:
 id="myLink" title="Click to do something" href="PleaseEnableJavascript.html" onclick="MyFunction();return false;">link text
Why better? because return false will prevent browser from following the link
best:
Use jQuery or other similar framework to attach onclick handler by element's ID.
$('#myLink').click(function(){ MyFunction(); return false; });
$('a').click( function() { your_code_here; return false; } );
 id="link" href="http://example.com/action">link text

Comments

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here.
    Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Online Training from India . or learn thru JavaScript Online Training from India. Nowadays JavaScript has tons of job opportunities on various vertical industry.
    ES6 Training in Chennai

    ReplyDelete

Post a Comment