I know how to fire an event in JavaScript, but I don't know how to make it cancelable. via event.preventDefault()
in event handler.
document.dispatchEvent(new CustomEvent("name-of-event", {}));
I have written the following code, but how is it possible in a native way, via event.preventDefault()
?
document.dispatchEvent(new CustomEvent("my-event",function keepGoing(result){
if(result){
// continue ...
}
}));
// And then in event listener:
document.addEventListener('my-event',function(event,keepGoing){
keepGoing(true);
// Or keepGoing(false);
});
If your custom event has the cancelable option set to true , you can use the Event. preventDefault() method to cancel it. document. addEventListener('my-custom-event', function (event) { // Cancel the event event.
Calling dispatchEvent() is the last step to firing an event. The event should have already been created and initialized using an Event() constructor. Note: When calling this method, the Event. target property is initialized to the current EventTarget .
Custom event definitions are event definitions that have been created from scratch in the event definition editor rather than having been generated from existing events by the event definition generator.
The CustomEvent
constructor takes a second options parameter, which you can use to make the event cancelable
. See the article Creating and triggering events on MDN.
var event = new CustomEvent("my-event", {
cancelable: true
})
document.addEventListener('my-event', function (event) {
event.preventDefault()
})
console.log(
document.dispatchEvent(event) ? 'Event was not cancelled' : 'Event was cancelled'
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With