Home » Web » Javascript » Using onclick for Javascript function instead of href

Using onclick for Javascript function instead of href

Many people will use Javascript function call directly into the href attribute of the link tag when they want to execute Javascript. This let them execute Javascript without having to have the fallback of having the browser scrolling to the top. The problem with this method, other than having client script into an attribute which is been created for anchor link and external link is that it displays the Javascript code in the status bar of the browser.

<a href='javascript:MyFunction(1,2,3)'>Click me</a>

To avoid this kind of behavior, which is not very clean, is to simply use the onclick attribut which is dedicated to receive Javascript’s call.

<a href='#' onclick="MyFunction(1,2,3);return false;">Click me</a>

As you can see, the onclick contain also a second Javascript’s statement which indicate the to the browser to not execute the link in the href attribute (the hash tag). This will prevent the browser to scroll up. In fact, you could specify a page to go if something goes wrong with the Javascript or if the user doesn’t have Javascript enable.

<a href='fallbackpage.html' onclick="MyFunction(1,2,3);return false;">Click me</a>

In that case, if Javascript is disable, the user will be redirected to the “fallbackpage.html”.

You can also not systematic use the `return false` and simply use directly the return of your function.

<a href='nextpage.aspx' onclick="return MyFunction(1,2,3);">Click me</a>

In that case, this will call the MyFunction fonction and if the result is false will do nothing with the navigation and if true will move the user to “nextpage.aspx”. This can be interesting in a scenario where you need to have to confirm something with the user or if you need to validate data before moving to the next step.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.