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)?
This works
One more thing that I noticed when using "href" with javascript:
The script in "href" attribute won't be executed if the time difference between 2 clicks was quite short.
For example, try to run following example and double click (fast!) on each link. The first link will be executed only once. The second link will be executed twice.
Reproduced in Chrome (double click) and IE11 (with triple click). In Chrome if you click fast enough you can make 10 clicks and have only 1 function execution.
Firefox works ok.
the best way to do this is with:
The problem is that this WILL add a hash (#) to the end of the page's URL in the browser, thus requiring the user to click the back button twice to go to the page before yours. Considering this, you need to add some code to stop event propagation. Most javascript toolkits will already have a function for this. For example, the dojo toolkit uses
to do so.
Having
javascript:
in any attribute that isn't specifically for scripting is an outdated method of HTML. While technically it works, you're still assigning javascript properties to a non-script attribute, which isn't good practice. It can even fail on old browsers, or even some modern ones (a googled forum post seemd to indicate that Opera does not like 'javascript:' urls).A better practice would be the second way, to put your javascript into the
onclick
attribute, which is ignored if no scripting functionality is available. Place a valid URL in the href field (commonly '#') for fallback for those who do not have javascript.I experienced that the javascript: hrefs did not work when the page was embedded in Outlook's webpage feature where a mail folder is set to instead show an url