When emitting a custom event with Javascript, the defaultPrevented
property is always false. Here is a short example that shows this behaviour:
var event = new CustomEvent("my-event", {detail: "something"});
document.addEventListener("my-event", function(ev) {
ev.preventDefault();
console.log(ev.detail);
});
document.dispatchEvent(event); // => "something" from console.log above
console.log(event.defaultPrevented); // => false
There is a link in MDN for CustomEvent.initCustomEvent()
that has an argument cancelable
(which I'm guessing is the problem here), but the method is deprecated. How can I check if preventDefault
was called in a custom event?
The second argument for the CustomEvent constructor accepts an object with the following properties:
bubbles - Boolean indicating if the event should buble
cancelable - Boolean indicating if the event is cancelable (here is the problem I had)
detail - Any custom data you want to pass along with the event.
In the example above, just add cancelable
and it gives the correct output:
var event = new CustomEvent("my-event", {detail: "something", cancelable: true});
document.addEventListener("my-event", function(ev) {
ev.preventDefault();
console.log(ev.detail);
});
document.dispatchEvent(event); // => "something" from console.log above
console.log(event.defaultPrevented); // => true
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