Return False Not Preventing Default w/ addEventListener

I was under the impression “return false” would always prevent the default action. However, for some reason it’s only working for me when I use the DOM Level 0 method of attaching the event handler. When I use addEventListener, the form still submits.

So, I have this method that works properly…


function init() {
     document.getElementById('contact_form').onsubmit = test;
}

function test() {
	return false;
}

But when I do it this way, the form still gets submitted. Can someone please explain what I’m missing?


function init() {
	document.getElementById('contact_form').addEventListener('submit', test, false);
}

function test() {
	return false;
}

Oh and it’s not an IE/addEventListener issue because I’m testing in Chrome & Firefox right now. I know the handler is being attached properly because I tested with an alert message.

To prevent the default when usung an eventlistener you need to use the preventDefault() method of the event and not just return false.

The IE equivalent processing requires that you set window.eventReturnValue = false.

Only when you use old style event handlers do you use return false.

See JavaScript By Example - Events: Prevent Default for an example of how to get it working for all browsers.

Thanks. Not sure why I was so sure that return false would work with addEventListener, but I stand corrected.

Adding to what Felgall has contributed, this will do it for you

window.onload=function()
{ document.getElementById(‘contact_form’).addEventListener(‘submit’, function(evt){evt.preventDefault()}, false);
}