Addeventlistener('keydown',handlekeydown,false) Vs. .onkeydown Working Differently For Replacing Typed Keystroke
I am using a 'keydown' event to replace specific characters typed in an input textbox. When I use: document.getElementById('inputText').onkeydown = handleInputTextKeydown; or the
Solution 1:
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 browserfunctionaddEvent(elem, event, fn) {
// allow the passing of an element id string instead of the DOM elemif (typeof elem === "string") {
elem = document.getElementById(elem);
}
functionlistenHandler(e) {
var ret = fn.apply(this, arguments);
if (ret === false) {
e.stopPropagation();
e.preventDefault();
}
return(ret);
}
functionattachHandler() {
// normalize the target of the eventwindow.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 calledvar ret = fn.call(elem, window.event);
// support an optional return false to be cancel propagation and prevent default handling// like jQuery doesif (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);
}
}
Post a Comment for "Addeventlistener('keydown',handlekeydown,false) Vs. .onkeydown Working Differently For Replacing Typed Keystroke"