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)?
The top answer is a very bad practice, one should never ever link to an empty hash as it can create problems down the road.
Best is to bind an event handler to the element as numerous other people have stated, however,
<a href="javascript:doStuff();">do stuff</a>
works perfectly in every modern browser, and I use it extensively when rendering templates to avoid having to rebind for each instance. In some cases, this approach offers better performance. YMMVAnother interesting tid-bit....
onclick
&href
have different behaviors when calling javascript directly.onclick
will passthis
context correctly, whereashref
won't, or in other words<a href="javascript:doStuff(this)">no context</a>
won't work, whereas<a onclick="javascript:doStuff(this)">no context</a>
will.Yes, I omitted the
href
. While that doesn't follow the spec, it will work in all browsers, although, ideally it should include ahref="javascript:void(0);"
for good measureIn addition to all here, the href is shown on browser's status bar, and onclick not. I think it's not user friendly to show javascript code there.
I use
A long way around but it gets the job done. use an A style to simplify then it becomes:
it worked for me using this line of code:
bad:
good:
better:
even better 1:
even better 2:
Why better? because
return false
will prevent browser from following the linkbest:
Use jQuery or other similar framework to attach onclick handler by element's ID.
Personally, I find putting javascript calls in the HREF tag annoying. I usually don't really pay attention to whether or not something is a javascript link or not, and often times want to open things in a new window. When I try doing this with one of these types of links, I get a blank page with nothing on it and javascript in my location bar. However, this is sidestepped a bit by using an onlick.