preventDefault() method of the
Event interface lets you prevent the default action of an event.
Preventing form submission
I’d say this is the most frequent use case for me. If a form has validation errors, you’ll want to stop it from submitting.
Given an HTML form:
You can stop it from submitting by listening to the
submit event and calling the
There are other things you can do, such as:
- Suppressing a link
- Disabling a checkbox
- Preventing typing inside an
I won’t get into them, though.
I would generally advise against disabling an element’s default behaviour unless you really need to.
Form validation is the only real use case for me.
The thing to understand is that the
preventDefault() method disables the default behaviour of an element.
The event must be cancelable
You can only call the
preventDefault() method if an event is cancelable.
There are two ways to find out:
- Check the MDN Web Docs
- Check the event’s
The MDN Web Docs
Let’s say I want to find out if the
submit event is cancelable. I would go to my search engine and look for “mdn submit event”. This takes me to the page for the
submit event. At the top of the page, I can see that the event is indeed cancelable:
The other way is to check the event’s
cancelable property. It will be
false depending on the event in question:
If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!