Categories
JavaScript Answers

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

Spread the love

To access the event object and call preventDefault() from a custom function that originates from the onclick attribute of an HTML tag, you can pass event as a parameter to the function.

To do this we write

HTML:

<button onclick="customFunction(event)">Click me</button>

JavaScript:

function customFunction(event) {
    event.preventDefault();
    // Your custom code here
}

In this example, when the button is clicked, the customFunction is called with the event object passed as a parameter.

Inside the function, you can access the event object and call preventDefault() to prevent the default action associated with the event, such as submitting a form or following a link.

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 *