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.

For instance, we write

<a href="/foo" onclick="yesJsLogin(event)">Lorem ipsum</a>

to add a link with the onclick attribute set to yesJsLogin(event).

to call the yesJsLogin function with the event object when we click on it.

Then we write

function yesJsLogin(e) {
  e.preventDefault();
  //...
}

to define the yesJsLogin function.

In it, we call e.preventDefault to stop the behavior of going to the href URL.

Conclusion

To disable href if onclick is executed with JavaScript, we call preventDefault.

Leave a Reply

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