Codemonkey Codemonkey - 2 days ago 4
Javascript Question

How can I preventDefault() on dispatchEvent?

I have a submit event handler on a form (to catch people submitting the form with , which sometimes I need to fire manually (triggered by the user clicking on something other than a submit button), via dispatchEvent.

I don't want it to actually submit the form though, but once dispatchEvent has been fired it seems I can't cancel it?

myForm.addEventListener('submit', function(e) {
e.preventDefault();
console.log(e.defaultPrevented); // false
});

myForm.dispatchEvent(new Event('submit', {'detail': 'mydetail'}));


In Chrome this still outputs
false
, but the form doesn't submit (the desired behaviour). In fact even if I remove the preventDefault() line it still doesn't submit?

However, Firefox is a different story, and always submits the form.

How can I change this?

Answer

By default created event is not. You have to make your event cancelable.

 myForm.dispatchEvent(new Event('submit', {'detail': 'mydetail', cancelable: true}))
Comments