JavaScript - href vs onclick for callback function on Hyperlink

Javascript

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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:

$('a').click( function(e) {e.preventDefault(); /*your_code_here;*/ return false; } );

Solution 3 - Javascript

In terms of javascript, one difference is that the this keyword in the onclick handler will refer to the DOM element whose onclick attribute it is (in this case the <a> element), whereas this in the href attribute will refer to the window object.

In terms of presentation, if an href attribute is absent from a link (i.e. <a onclick="[...]">) then, by default, browsers will display the text cursor (and not the often-desired pointer 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 that href in a separate window using either a shortcut or context menu. This is not possible when specifying an action only via onclick.


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:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<a id="link" href="http://example.com/action">link text</a>
<script type="text/javascript">
    $('a#link').click(function(){ /* ... action ... */ })
</script>

Solution 4 - Javascript

EDITOR WARNING: See the comments, the use of 'nohref' is incorrect in this answer.

I use

Click <a nohref style="cursor:pointer;color:blue;text-decoration:underline"
onClick="alert('Hello World')">HERE</a>

A long way around but it gets the job done. use an A style to simplify then it becomes:

<style> A {cursor:pointer;color:blue;text-decoration:underline; } </style> 
<a nohref onClick="alert('Hello World')">HERE</a>

Solution 5 - Javascript

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. YMMV

Another interesting tid-bit....

onclick & href have different behaviors when calling javascript directly.

onclick will pass this context correctly, whereas href 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 a href="javascript:void(0);" for good measure

Solution 6 - Javascript

In 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.

Solution 7 - Javascript

the best way to do this is with:

<a href="#" onclick="someFunction(e)"></a>

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

dojo.stopEvent(event);

to do so.

Solution 8 - Javascript

This works

<a href="#" id="sampleApp" onclick="myFunction(); return false;">Click Here</a>

Solution 9 - Javascript

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.

Solution 10 - Javascript

it worked for me using this line of code:

<a id="LinkTest" title="Any Title"  href="#" onclick="Function(); return false; ">text</a>

Solution 11 - Javascript

First, having the url in href is best because it allows users to copy links, open in another tab, etc.

In some cases (e.g. sites with frequent HTML changes) it is not practical to bind links every time there is an update.

Typical Bind Method

Normal link:

<a href="https://www.google.com/">Google<a/>

And something like this for JS:

$("a").click(function (e) {
    e.preventDefault();
    var href = $(this).attr("href");
    window.open(href);
    return false;
});

The benefits of this method are clean separation of markup and behavior and doesn't have to repeat the function calls in every link.

No Bind Method

If you don't want to bind every time, however, you can use onclick and pass in the element and event, e.g.:

<a href="https://www.google.com/" onclick="return Handler(this, event);">Google</a>

And this for JS:

function Handler(self, e) {
    e.preventDefault();
    var href = $(self).attr("href");
    window.open(href);
    return false;
}

The benefit to this method is that you can load in new links (e.g. via AJAX) whenever you want without having to worry about binding every time.

Solution 12 - Javascript

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.

Solution 13 - Javascript

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.

<script>
function myFunc() {
	var s = 0;
	for (var i=0; i<100000; i++) {
		s+=i;
	}
	console.log(s);
}
</script>
<a href="javascript:myFunc()">href</a>
<a href="#" onclick="javascript:myFunc()">onclick</a>

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.

Solution 14 - Javascript

The most upvoted answer is obsolete today

I would recommend the exact opposite, see step by step with reasons:

good:

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

It depends, might be good, because crawlers follows href targets and if there is any meaningful content produced by MyFunction() (dynamic link), it is followed more likely than in the click event, which may have multiple or none listeners.

bad:

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

# means meaningless link, crawlers are often interested only in first x links, so it can prevent them to follow some meaningful links later in the page.

worse:

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

Same as previous plus return false prevents following the link. If some other scripts want to add another listener and update the target (say to redirect via proxy), they can't without modifying the onclick (okay, it's just a minor setback as such use cases are rather theoretical).

worst:

Use jQuery or other similar framework to attach onclick handler by element's ID.

$('#myLink').click(function(){ MyFunction(); return false; });

jQuery is outdated in 2020+ and should not be used in new projects.

Events in href

The href attribute handler doesn't get the event object, so the handler doesn't implicitly see which link was the source. You can add it in onclick handler, which fires before the href is followed:

<a href="javascript:my_function(event2)" onclick="event2=event">
  JS based link
</a>

<script>
function my_function(e) {
  console.log(e.target); // the source of the click
  if(something) location.href = ...; // dynamic link
}
</script>

Solution 15 - Javascript

 <hr>
			<h3 class="form-signin-heading"><i class="icon-edit"></i> Register</h3>
			<button data-placement="top" id="signin_student" onclick="window.location='signup_student.php'" id="btn_student" name="login" class="btn btn-info" type="submit">Student</button>
			<div class="pull-right">
				<button data-placement="top" id="signin_teacher" onclick="window.location='guru/signup_teacher.php'" name="login" class="btn btn-info" type="submit">Teacher</button>
			</div>
		</div>
			<script type="text/javascript">
				$(document).ready(function(){
				$('#signin_student').tooltip('show'); $('#signin_student').tooltip('hide');
				});
			</script>	
			<script type="text/javascript">
				$(document).ready(function(){
				$('#signin_teacher').tooltip('show'); $('#signin_teacher').tooltip('hide');
				});
			</script>	

Solution 16 - 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

Solution 17 - Javascript

<a href="#" onclick="try{FUNCTION_YOU_WANT()}catch(e){}return false">click here</a>

Solution 18 - Javascript

This works as well

<a (click)='myFunc()'>Click Here </a>

(onclick) did not work for me in an Angular project with bootstrap.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSkunkSpinnerView Question on Stackoverflow
Solution 1 - JavascriptdempView Answer on Stackoverflow
Solution 2 - JavascriptParandView Answer on Stackoverflow
Solution 3 - JavascriptAdamView Answer on Stackoverflow
Solution 4 - JavascriptClif CollinsView Answer on Stackoverflow
Solution 5 - JavascriptslothstronautView Answer on Stackoverflow
Solution 6 - JavascriptKamareyView Answer on Stackoverflow
Solution 7 - Javascriptlinusthe3rdView Answer on Stackoverflow
Solution 8 - JavascriptTitusMixView Answer on Stackoverflow
Solution 9 - JavascriptzombatView Answer on Stackoverflow
Solution 10 - JavascriptOmar Yassin CarcelenView Answer on Stackoverflow
Solution 11 - JavascriptjchavannesView Answer on Stackoverflow
Solution 12 - JavascriptPeterView Answer on Stackoverflow
Solution 13 - JavascriptkolobokView Answer on Stackoverflow
Solution 14 - JavascriptJan TuroňView Answer on Stackoverflow
Solution 15 - JavascriptAndrewView Answer on Stackoverflow
Solution 16 - JavascriptChristianView Answer on Stackoverflow
Solution 17 - JavascriptAbdulRahman AlShamiriView Answer on Stackoverflow
Solution 18 - JavascriptMohitn29View Answer on Stackoverflow