[javascript] 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)?

This question is related to javascript href

The answer is


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.


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.


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


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.


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.


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.


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

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.


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>

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


This works

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

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>

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

it worked for me using this line of code:

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