How to move an element to left, right, up and down using arrow keys in jQuery

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the jQuery keydown() method

You can use the jQuery keydown() method in combination with the animate() method to move an element such as <div> in left, right, up and down direction through pressing the corresponding arrow keys on the keyboard. Check out the example below.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="UTF-8">
  • <title>jQuery Move DIV Element with Arrow Keys</title>
  • <style type="text/css">
  •     .box{
  •         width: 100px;
  •         height: 100px;
  •         position: relative;
  •         margin: 200px auto 0;
  •         background: yellowgreen;
  •     }
  • </style>
  • <script src="http://code.jquery.com/jquery.js"></script>
  • <script type="text/javascript">
  • $(document).keydown(function(e){
  •     switch (e.which){
  •     case 37:    //left arrow key
  •         $(".box").finish().animate({
  •             left: "-=50"
  •         });
  •         break;
  •     case 38:    //up arrow key
  •         $(".box").finish().animate({
  •             top: "-=50"
  •         });
  •         break;
  •     case 39:    //right arrow key
  •         $(".box").finish().animate({
  •             left: "+=50"
  •         });
  •         break;
  •     case 40:    //bottom arrow key
  •         $(".box").finish().animate({
  •             top: "+=50"
  •         });
  •         break;
  •     }
  • });
  • </script>
  • </head>
  • <body>
  •     <p><strong>Note:</strong> Click inside the viewport and press the arrow keys to move the box.</p>
  •     <div class="box"></div>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.