How to access event object to call preventDefault from custom function originating from onclick attribute of tag with JavaScript?

Spread the love

Sometimes, we want to access event object to call preventDefault from custom function originating from onclick attribute of tag with JavaScript.

In this article, we’ll look at how to access event object to call preventDefault from custom function originating from onclick attribute of tag with JavaScript.

How to access event object to call preventDefault from custom function originating from onclick attribute of tag with JavaScript?

To access event object to call preventDefault from custom function originating from onclick attribute of tag with JavaScript, we call the onclick handler with event.

For instance, we write

<a href="http://example.com" onclick="sayHi(event);">Click to say Hi</a>

to add a link that sets the onclick attribute to call sayHi with the event object.

Then we write

function sayHi(e) {
  e.preventDefault();
  alert("hi");
}

to call e.preventDefault in the sayHi function.

Conclusion

To access event object to call preventDefault from custom function originating from onclick attribute of tag with JavaScript, we call the onclick handler with event.

Leave a Reply

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