addEventListener('keydown',handlekeydown,false) vs. .onkeydown working differently for replacing typed keystroke

StackOverflow https://stackoverflow.com/questions/19609537

Frage

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 JQuery equivalent:

$('#inputText').on('keydown',handleInputTextKeydown);

I get the expected result - e.g. the keypress Shift+i displays as 'í'.

However if I use addEventListner as the keydown hook:

var tb = document.getElementById('inputText');
tb.addEventListener('keydown', handleInputTextKeydown, false); 

the input textbox displays both my substitute character (í) and 'I' (uppercase i) 'íI'.

Why does the addEventListener method differ from the two 'onkeydown' hooks?

My test browser is IE 11.

BTW: I am using a variant of the keydown text replace method that was in another stackoverflow post:

newKey = keyMap[keyPressed];                // Look for this key in our list of accented key shortcuts
    if (newKey === undefined) {
            return true;                        // Not in our list, let it bubble up as is
        } else {

        var oldValue, start, end;
        oldValue = this.value;                  // Insert the updated key into the correct position within the edit textbox.
        if (typeof this.selectionStart == "number" && typeof this.selectionEnd == "number") {
            start = this.selectionStart;
            end = this.selectionEnd;
            this.value = oldValue.slice(0, start) + newKey + oldValue.slice(end);
        }
                                                // Move the caret
        this.selectionStart = this.selectionEnd = start + 1;
        return false;
War es hilfreich?

Lösung

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);
    }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top