0

I am trying to create my own vanilla JS lightbox. I'have ran into an issue with keyboard control via KeyDown event. Here is the code:

function keyDown(e) {

    if(e.keyCode === 27) {

        closeModal();
    }
    else if(e.keyCode === 37 || 38 || 100 || 104 || 65 || 87) {

        previousSlide();

    }
    else if(e.keyCode === 39 || 40 || 102 || 98 || 68 || 83) {

        nextSlide();

    }
}

The first statement (esc key for closing modal) works properly. However, all other pressed keys (all but esc key) triggers the second function previousSlide(). I have tried all kinds of stuff, for example omitting every key codes but one, returning all false, but to no avail.

If I replace that code with good ol' case & switch, it works as intended:

function keyDown(e) {

switch (e.keyCode) {
    case 27:
    closeModal();
    break;
    case 37:
        previousSlide();
        break;
    case 38:
        previousSlide();
        break;
    case 39:
        nextSlide();
        break;
    case 40:
        nextSlide();
        break;

}

The function is fired by addEventListener method:

    function assignKeys() {

    window.addEventListener('keydown', keyDown, false);
}

Did I miss something? Please help. Thanks.

HynekS
  • 2,738
  • 1
  • 19
  • 34
  • There were probably a pair of parentheses missing around the list of key codes. If I do this is: else if(e.keyCode === (39 || 40 || 102 || 98 || 68 || 83)) it works. EDIT: It works only for the first key :( – HynekS Oct 11 '17 at 13:11
  • `O.K., I worked it out.` , no you never. That's not the reason.. – Keith Oct 11 '17 at 13:13
  • All right. I tried to put the keycodes in array as advised in the link on top, and now it hopefully seems to work. – HynekS Oct 11 '17 at 13:38

0 Answers0