A JavaScript Curiosity Regarding addEventListener

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.

4 thoughts on “A JavaScript Curiosity Regarding addEventListener

  1. 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

  2. I have been killing myself trying to find an answer to this – thanks Rob for asking and Abhishek for answering.

Leave a Reply

Your email address will not be published. Required fields are marked *