jQuery Move div with arrow keys

I’m trying to move a div using the arrow keys. I have the following code which is not working for me. Do you see anything wrong with it. Check jsfiddle at http://jsfiddle.net/N5Ltt/1/

$(document).keydown(function(e) {
    switch (e.which) {
    case 37:
        $('div').stop().animate({
            left: '-= 10'
        }); //left arrow key
        break;
    case 38:
        $('div').stop().animate({
            top: '-= 10'
        }); //up arrow key
        break;
    case 39:
        $('div').stop().animate({
            left: '+= 10'
        }); //right arrow key
        break;
    case 40:
        $('div').stop().animate({
            top: '+= 10'
        }); //bottom arrow key
        break;
    }
})

  • Press left and right arrow to change image?
  • Javascript onChange arrow keys
  • JS ArrowDown addEventListener for several elements in loop (demo)
  • How do you make up and down arrows highlight items in a list? (jQuery)
  • How can I handle ArrowKeys and < (Greater Than) in a Javascript function? Which event and which code (charCode Or keyCode)?
  • Navigate through list using arrow keys? (JavaScript/JQ)
  • JS ArrowDown addEventListener for several elements in loop (demo)
  • Detecting Arrow key press in IE via javascript/jQuery
  • How can I handle ArrowKeys and < (Greater Than) in a Javascript function? Which event and which code (charCode Or keyCode)?
  • Disable arrow key scrolling in users browser
  • Simulate left and right arrow key event with javascript
  • How to disable page scrolling in FF with arrow keys
  • One Solution collect form web for “jQuery Move div with arrow keys”

    There are two things you need to do:

    1. Your <div> needs position: absolute or your top and left properties won’t do anything.
    2. jQuery doesn’t know what '-= 10' means but it does understand '-=10'. You might want to go all the way to '-=10px' as that’s more common but the px isn’t necessary.

    Updated fiddle: http://jsfiddle.net/ambiguous/N5Ltt/2/

    You’re seeing the animation stop when you hold down an arrow key because you call .stop on each keydown and that stops the animation. The animation works using a timer and .stop stops the timer; if the keyboard’s repeat rate is faster than the first iteration of the timer then no animation happens when you hold down an arrow key. You’re only moving by 10px at a time so you could just do a straight non-animated move by 10px using .css:

    $div.css('left', $div.offset().left - 10);
    

    Non-animated version: http://jsfiddle.net/ambiguous/N5Ltt/3/