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)?
In terms of javascript, one difference is that the
this
keyword in theonclick
handler will refer to the DOM element whoseonclick
attribute it is (in this case the<a>
element), whereasthis
in thehref
attribute will refer to thewindow
object.In terms of presentation, if an
href
attribute is absent from a link (i.e.<a onclick="[...]">
) then, by default, browsers will display thetext
cursor (and not the often-desiredpointer
cursor) since it is treating the<a>
as an anchor, and not a link.In terms of behavior, when specifying an action by navigation via
href
, the browser will typically support opening thathref
in a separate window using either a shortcut or context menu. This is not possible when specifying an action only viaonclick
.However, if you're asking what is the best way to get dynamic action from the click of a DOM object, then attaching an event using javascript separate from the content of the document is the best way to go. You could do this in a number of ways. A common way is to use a javascript library like jQuery to bind an event:
Putting the onclick within the href would offend those who believe strongly in separation of content from behavior/action. The argument is that your html content should remain focused solely on content, not on presentation or behavior.
The typical path these days is to use a javascript library (eg. jquery) and create an event handler using that library. It would look something like: