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.