Sometimes, we want to prevent anchor behavior with JavaScript.
In this article, we’ll look at how to prevent anchor behavior with JavaScript.
How to prevent anchor behavior with JavaScript?
To prevent anchor behavior with JavaScript, we return false
in the event handler.
For instance, we write
<a href="no-script.html" id="myLink">link</a>
to add a link.
Then we write
document.getElementById("myLink").onclick = () => {
// ...
return false;
};
to get the link with getElementById
.
And then we set its onclick
property to a function that’s called when the link is clicked.
We return false
to stop the default behavior.
Conclusion
To prevent anchor behavior with JavaScript, we return false
in the event handler.