Several events can be fired when we access a website. These events could be a button click, filling out a form and submitting it, closing a tab, clicking a checkbox, or scrolling a page. All of these are events.
In JavaScript, these events’ actions can be canceled. Yes, they can be kept from executing the default action that is associated with it. This is done using the preventDefault()
method of an event. The preventDefault()
method of an event is used to stop a cancelable event from executing.
event.preventDefault();
The following code stops a checkbox from executing its default action by using the preventDefault()
method.
Some event actions cannot be prevented using the
event.preventDefault()
. In order to check if an event can be prevented, you can check itsevent.cancelable
property. This property can either befalse
ortrue
.
The oninput
event on an input
element is not cancelable. Therefore, it will still allow a user to input strings of characters. Take a look at the example below. There will be an alert when you input your texts, and you will still be able to input more because the oninput
event action is not cancelable.