Difference between JavaScript function in href and onclick

By Saruque Ahamed Mollick

In this JavaScript post, I am going to clear the difference between JavaScript function in href and onclick. You will also learn where to use JavaScript function in href and onclick. In both the cases, you will get the same result but there are some behavioural differences. I am here to clear all the confusions arising in your mind regarding this.

Difference between JavaScript function in href and onclick

Here I am going to show you example of JavaScript function implementation using href and onclick both

<a href="javascript:inHrefFunction()">Click Me!</a>

This one is the implementation of JavaScript function in href.



<a href="#" onclick="onclickFunction()">Click Me!</a>

This one is the implementation of JavaScript function in onclick.

Basically, there is no difference in the performance.

How to write inline JavaScript code in HTML file

But the first one will fail for sure for the browsers where JavaScript is not enabled.
And the second one will also fail but it will be better if the href pointed to a URL for users without JS enabled.

In onclick, you can pass this as an argument but you can not do it for href.

Let’s see the below example,

<a href="#" onclick="document.write(this.innerHTML)">I am onclick</a>

Here you will get output:

I am onclick

But if you call JavaScript from the href:

<a href="javascript:document.write(this.innerHTML)">I am href</a>

Here the output will be like this:

undefined

If you add JavaScript in href and your browser is not JS enabled then it is a great problem.
But if you use JavaScript in onclick and add return false; or return doAnythingYouWant(); it will be better for you. As in this case if your browser is not JS enabled then it will navigate to the page you wanted. And if Js is enabled then you can display something with JS.

You can Also read,

Guess The Number Game Using JavaScript

How to run multiple JavaScript functions onclick

 

Leave a Reply

Your email address will not be published. Required fields are marked *