Syed
Syed

Reputation: 563

addEventListener input keycode not working

Is there a way of getting the Keycode that is being pressed when addEventListener inputis fired?

<p contentEditable="true" id="newTask">New task</p>

document.getElementById("newTask").addEventListener("input", function(e) {
            if(e.keyCode == 13 || e.which == 13)
            {
                console.log("input event fired");
                // return false; // returning false will prevent the event from bubbling up.
            }
            else
            {
                console.log("others: " + e);
                // return true;
            }
        }, false);

Upvotes: 0

Views: 183

Answers (1)

Hunter Mitchell
Hunter Mitchell

Reputation: 7293

This is because you should be using the keypress event, rather than input.

Try the following:

document.getElementById("newTask").addEventListener("keypress", function(e) {
        if(e.keyCode == 13 || e.which == 13)
        {
            console.log("input event fired");
            // return false; // returning false will prevent the event from bubbling up.
        }
        else
        {
            console.log("others: " + e);
            // return true;
        }
    }, false);

Upvotes: 1

Related Questions