Member-only story
Have you ever encountered situations where the browser performs undesired actions after clicking certain buttons or links? For instance, submitting a form reloads the entire page or opening a link downloads a file automatically. With JavaScript’s preventDefault()
method, developers gain control over native browser behaviors and tailor them according to project requirements.
Let's delve deeper into this useful feature!
What is preventDefault()
?
preventDefault()
is a built-in method belonging to the Event
interface in JavaScript. When invoked inside an event handler, it prevents the browser from executing its default action associated with the specific event. To utilize this technique, simply pass the relevant event object to the callback function and invoke the preventDefault()
method accordingly.
Syntax:
element.addEventHandler(type, listener[, useCapture]);
function listener(event) {
event.preventDefault();
}
Here are some examples.