Sometimes, we want to disable href if onclick is executed with JavaScript.
In this article, we’ll look at how to disable href if onclick is executed with JavaScript.
How to disable href if onclick is executed with JavaScript?
To disable href if onclick is executed with JavaScript, we call preventDefault
to stop the default navigation action.
For instance, we write
document.getElementsById("ignore-click").addEventListener("click", (event) => {
event.preventDefault();
//...
});
to select the link with getElementById
.
Then we call addEventListener
on it to add a click listener.
In it, we call event.preventDefault
to stop the default navigation action.
Then we can run our onclick code after that.
Conclusion
To disable href if onclick is executed with JavaScript, we call preventDefault
to stop the default navigation action.