Search code examples
javascripteventskeypress

Tab keypress event doesn't work (native JavaScript)


So I've been learning JavaScript recently and I can't seem to figure out why the following code doesn't work. I used a keypress event on "enter" (keypress code 13, in case anyone's curious) and it worked perfectly. However I can't get keypress code 9 (tab) to work.

The function listItemTab by itself seems to work, but it never gets into my if-statement (my console.log never executes).

Here's the codepen I've been working on, so you can see all the code in context to my html.

var myList = document.getElementById("my-list");
var listItems = myList.querySelectorAll("li");
var inputs = myList.querySelectorAll("input");

for(var i = 0; i < listItems.length; i++){
    inputs[i].addEventListener("keypress", listItemTab);
}

function listItemTab(event){
    if(event.which === 9){
        console.log("tab pressed");
    }
}

Thanks in advance for any help! :)


Solution

  • Try using the keydown event instead of the keypress event. Keydown fires first. Also prevent the default action if you want to stay inside the input. (if you don't want to stay inside the input, just remove that line)

    inputs[i].addEventListener("keydown", listItemTab);
    
    // not working yet
    function listItemTab(event){    
        event.preventDefault();
        if(event.which === 9){
            console.log("tab pressed");     
        }
    }