JavaScript function in href vs. onclick

SkunkSpinner picture SkunkSpinner · Jul 1, 2009 · Viewed 1.5M times · Source

I want to run a simple JavaScript function on a click without any redirection.

Is there any difference or benefit between putting the JavaScript call in the href attribute (like this:

<a href="javascript:my_function();window.print();">....</a>

) vs. putting it in the onclick attribute (binding it to the onclick event)?

Answer

demp picture demp · Jul 5, 2012

bad:

<a id="myLink" href="javascript:MyFunction();">link text</a>

good:

<a id="myLink" href="#" onclick="MyFunction();">link text</a>

better:

<a id="myLink" href="#" onclick="MyFunction();return false;">link text</a>

even better 1:

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

even better 2:

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

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; });