Because you have to prevent the default behavior with the .addEventListener()
version.
Returning false at the end of the handler to prevent the default behavior is a jQuery-specific feature and a feature of the .onkeydown
property, but not something that works with .addEventListener('keydown')
.
You will need to call e.preventDefault()
(for modern browsers) or set e.returnValue = false
(for non-standard browsers).
This is more than you need to solve your problem, but when working in plain javascript, I use a cross browser event handling stub that allows me to return false like this:
// refined add event cross browser
function addEvent(elem, event, fn) {
// allow the passing of an element id string instead of the DOM elem
if (typeof elem === "string") {
elem = document.getElementById(elem);
}
function listenHandler(e) {
var ret = fn.apply(this, arguments);
if (ret === false) {
e.stopPropagation();
e.preventDefault();
}
return(ret);
}
function attachHandler() {
// normalize the target of the event
window.event.target = window.event.srcElement;
// make sure the event is passed to the fn also so that works the same too
// set the this pointer same as addEventListener when fn is called
var ret = fn.call(elem, window.event);
// support an optional return false to be cancel propagation and prevent default handling
// like jQuery does
if (ret === false) {
window.event.returnValue = false;
window.event.cancelBubble = true;
}
return(ret);
}
if (elem.addEventListener) {
elem.addEventListener(event, listenHandler, false);
} else {
elem.attachEvent("on" + event, attachHandler);
}
}