Link to activate JavaScript function

Which "href" value, "#" or "javascript:void(0)" should I use for JavaScript links?

When creating an application using pure JavaScript, sometimes you need to trigger a function when the user clicks a link.

Generally, you can do this in 2 ways.

Suppose the function you want to execute is calledhandleClick():

function handleClick() {
  alert('clicked')
}

The first method is to use a link like this:

<a href="#" onclick="handleClick()">Click here</a>

The second method is to use

<a href="javascript:void(0)" onclick="handleClick()">Click here</a>

They are all very similar grammars, the only difference ishrefAttribute value.

first of allhref="#"And the second one ishref="javascript:void(0)". You may also see this syntaxhref="javascript:;", Which is equivalent to the second one.

Now, what is the difference between the behavior of these two methods?

When the user clickshref="#"Link youhave toMake sure you come backfalseFrom the event handler, otherwise the browser will scroll back to the top of the page:

function handleClick() {
  alert('clicked')
  return false
}

In addition, even if you add this feature, the browser will scroll back to the top of the page if JavaScript is disabled or cannot be executed for some reason. This is almost always something to avoid, so I will personally use the second form,href="javascript:void(0)".

Two wayshandleClick()If JavaScript is disabled or there is an error in JavaScript, the function will not be called, so JavaScript execution will stop.

To prevent this, you canhrefAs a fallback, the browser will therefore use the GET HTTP method to move the user to a specific page, although this is not always possible or convenient.

But this is best practice. Best practices are not always convenient, but you must take them into consideration during the design phase of your application, because you can’t just build for the ideal use case and ignore all things that might go wrong .

If something goes wrong, the user will blame you, and your broken link 🙂

Download mine for freeJavaScript beginner's manual


More js tutorials: