Categories
JavaScript Answers

How to disable href if onclick is executed with JavaScript?

Spread the love

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.

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 *