Search code examples
jqueryfunctiononkeypress

jQuery - Binding key presses to function


I know that this question has been asked and answered before, and I have found the answer already, but I had an issue for which I required some follow-up information, and as my rep is too low, I cannot comment on the relevant answer to ask for it!

I am using sygmoral's answer for this post, which should be the second answer down the page. I am using two functions to operate an image slider, one to slide left, and one to slide right. When clicking the on-screen buttons with the mouse cursor, each function operates perfectly, but when using sygmoral's function for key presses, only one of the left/right arrow keys triggers the function properly...

The keypress function code goes like this:

    $(document).keydown(function(e){
        switch(e.which) {
            case 37:
            slideLeft();

            case 39:
            slideRight();

            default: return;                
        }
        e.preventDefault();
    });

case 39 works as it should. case 37 triggers the slideLeft() function, and the image slides left, but then immediately slides back to the right. If I swap cases 39 and 37, the opposite happens. Basically, only the second case will work properly.

Can anyone offer me a suggestion as to why this might be?


Solution

  • you missing break; keyword in each branch of switch statement so if you press left arrow you will get into case 37 - slideLeft() is processed and then rest of the code too (slideRight();return;)

    see switch documentation on MDN.

    here is what you need:

    $(document).keydown(function(e){
        switch(e.which) {
            case 37:
                slideLeft();
                break;
            case 39:
                slideRight();
                break; // isn't needed in your case
            default:
                return;                
        }
        e.preventDefault();
    });