Skip to content Skip to sidebar Skip to footer

How Use Keyboard Arrow Keys To Move A Div 100px Left/right Respectively

I have a div with an id of bottom_arrow and I want to use my keyboard arrows left/right to move the div left and right 100px. How can I do this?

Solution 1:

As a rule keypress events go to an input or some control that has focus, if you need them generally on a page, which is a sometimes a little frowned upon due to removing standard behavior, then bind the keydown event to the whole document.

$('body').keydown(function(event) {
    switch (event.keycode) {
        case37: // left arrow key
           $('#bottom_arrow').animate({ 'left': '-=100' });
           break;
        case39: // right arrow key
           $('#bottom_arrow').animate({ 'left': '+=100' });
           break;
    }
});

I have used keydown, rather than keypress as a user would expect it to trigger whilst pressing the key.

Solution 2:

$('body').keydown(function(event) {
    switch (event.keycode) {
        case37: // left arrow key
           $('#bottom_arrow').animate({ 'left': '-=100' });
           break;
        case39: // right arrow key
           $('#bottom_arrow').animate({ 'left': '+=100' });
           break;
    }
});

Solution 3:

According to Jquery documentation, use event.which instead.

$('body').keydown(function(event) {
    switch (event.which) {
        case37: // left arrow key
            $('#bottom_arrow').animate({ 'left': '-=100' });
            break;
            case39: // right arrow key
            $('#bottom_arrow').animate({ 'left': '+=100' });
            break;
    }
});

Post a Comment for "How Use Keyboard Arrow Keys To Move A Div 100px Left/right Respectively"