Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript function in href vs. onclick

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)?

like image 518
SkunkSpinner Avatar asked Jul 01 '09 18:07

SkunkSpinner


People also ask

What is the difference between href and onclick?

In the href also serves keyboard navigation without the mouse. If your website is required to function without Javascript then you have to use onclick so the href can have a link in it. Adding the action in a separate Javascript file fails to keep code & data bound tightly.

Can we call JavaScript function in href?

In JavaScript, you can call a function or snippet of JavaScript code through the HREF tag of a link. This can be useful because it means that the given JavaScript code is going to automatically run for someone clicking on the link. HREF refers to the “HREF” attribute within an A LINK tag (hyperlink in HTML).

Can we pass function in href?

The anwer is: not possible.

Is it bad to use onclick attribute?

It's a new paradigm called "Unobtrusive JavaScript". The current "web standard" says to separate functionality and presentation. It's not really a "bad practice", it's just that most new standards want you to use event listeners instead of in-lining JavaScript.


1 Answers

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; }); 
like image 113
demp Avatar answered Oct 01 '22 15:10

demp