Sometimes, we want to access event to call preventdefault from custom function originating from onclick with JavaScript.
In this article, we’ll look at how to access event to call preventdefault from custom function originating from onclick with JavaScript.
How to access event to call preventdefault from custom function originating from onclick with JavaScript?
To access event to call preventdefault from custom function originating from onclick with JavaScript, we get the event object from the event handler function’s parameter.
For instance, we write
<a href="#">Click to say Hi</a>
to add a link.
Then we show an alert when we click on the link by writing
const a = document.querySelector("a");
a.onclick = (e) => {
e.preventDefault();
alert("hi");
};
We select the link with querySelector
.
Then we set its onclick
property to a function that calls e.preventDefault
to stop the default behavior of navigation to the URL set as the href attribute’s value.
Instead, we call alert
with 'hi'
to show an alert box.
Conclusion
To access event to call preventdefault from custom function originating from onclick with JavaScript, we get the event object from the event handler function’s parameter.