Search code examples
javascriptjquerykeypresskeydown

keydown function assigned to two keys but is fired when any key is pressed


Q: I assigned keydown to ONLY 2 keys, however, if i press any keyboard key, the script is fired. Can someone tell me if this is a formatting issue, just by looking at the script?

This keydown jQuery works for me, when the right arrow is pressed a modal moves to the next, and when the left key is pressed it will trigger the previous modal.

$("div[id^='myModal']").keydown(function(e){
    var currentModal = $(this);
    if (e.which == 39){
    }else{
  currentModal.modal('hide');
  currentModal.closest("div[id^='myModal']").prevAll("div[id^='myModal']").first().modal('show');  
    }
     var currentModal = $(this);
    if (e.which == 37){
    }else{
  currentModal.modal('hide');
  currentModal.closest("div[id^='myModal']").nextAll("div[id^='myModal']").first().modal('show');
    }
});


Solution

  • Problems arise from your use of the if statements. Looks to me as if you should change your code:

    $("div[id^='myModal']").keydown(function(e){
            var currentModal = $(this);
            if (e.which === 39) {
              currentModal.modal('hide');
              currentModal.closest("div[id^='myModal']").prevAll("div[id^='myModal']").first().modal('show');  
            } else if (e.which === 37) {
              currentModal.modal('hide');
              currentModal.closest("div[id^='myModal']").nextAll("div[id^='myModal']").first().modal('show');
            }
        });

    Basically, what your code says is "If the left arrow key is pressed do nothing, otherwise do something with the previous modal" and then "If the right arrow key is pressed do nothing, otherwise do something with the next modal".