A JavaScript Curiosity Regarding addEventListener
by Rob Larsen
I’m wondering why this code fails to stop a form submission
document.forms[0].addEventListener("submit",falsify, false);
function falsify() {
return false;
}
and this code successfully kills it?
document.forms[1].onsubmit = falsify;
function falsify() {
return false;
}
Try it out (Firefox/Safari/Chrome/Opera only- there’s no addEventListener support in Internet Explorer). The form action on both is an alert. The first executes every time. The second never does.
Anyone out there know enough about the inner workings on addEventListener to explain why those two similar code blocks behave so differently? I’ve poked around a lot of the usual suspects (mdc, ppk, w3c) and haven’t seen anything that speaks to the above behavior, so I’m opening it up to the Internet. Hopefully someone out there can satisfy my curiosity on this matter.
Abhishek Says:
April 2nd, 2009 at 11:25 am
The first form is submitted as that its implementation-defined default action. However, per the W3C spec, the submit event has the property of being cancelable[1]. That is, its preventDefault method can be called to suppress the default action[2].
For example:
document.forms[0].addEventListener('submit', function (e) { e.preventDefault(); }, false);[1] http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-htmlevents
[2] http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow-cancelation
rob Says:
April 2nd, 2009 at 11:56 am
This is why I love the internet.
Thanks!
Rohan Says:
June 7th, 2009 at 9:08 pm
I have been killing myself trying to find an answer to this – thanks Rob for asking and Abhishek for answering.
rob Says:
June 7th, 2009 at 9:24 pm
Glad to be of service