Categories
JavaScript Answers

How to prevent href=”#” link from changing the URL hash with JavaScript?

Spread the love

Sometimes, we want to prevent href="#" link from changing the URL hash with JavaScript.

In this article, we’ll look at how to prevent href="#" link from changing the URL hash with JavaScript.

How to prevent href="#" link from changing the URL hash with JavaScript?

To prevent href="#" link from changing the URL hash with JavaScript, we call preventDefault.

For instance, we write

<a href="/foo/bar" class="link">Foo: Bar</a>

to add a link.

Then we write

addEventListener("click", (ev) => {
  if (ev.target.classList.contains("link")) {
    ev.preventDefault();
    //...
  }
});

to add a click listener to window with addEventListener.

In the event listener, we check if the element being clicked on has class link with classList.contains.

If it’s true, then we call preventDefault to stop the default navigation behavior.

Conclusion

To prevent href="#" link from changing the URL hash with JavaScript, we call preventDefault.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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