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.