How to move an element with arrow keys in jQuery
In this tutorial, we are going to see how to move an element with arrow keys in jQuery. You can simply use the method keydown() of jQuery with animate() method to move an element in left, right, up, and down by pressing the matching arrow keys. Check out the example below.
HTML Code:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Move an element with arrow keys</title> <style type="text/css"> /* Put the CSS Style Here */ </style> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script type="text/javascript"> // Put the jQuery code Here </script> </head> <body> <p><b>Click here to move the object.</b></p> <div class="myDiv"></div> </body> </html>[st_adsense]
jQuery Code:
$(document).keydown(function(e){ switch (e.which){ case 37: // key left, right, up, and down $(".myDiv").finish().animate({ left: "-=10" }); break; case 38: // key up $(".myDiv").finish().animate({ top: "-=10" }); break; case 39: // key right $(".myDiv").finish().animate({ left: "+=10" }); break; case 40: // key down $(".myDiv").finish().animate({ top: "+=10" }); break; } });[st_adsense]
CSS Code:
.myDiv { width: 150px; height: 53px; position: relative; margin: 100px auto 0; background: url("https://1.bp.blogspot.com/-I-a7SivlqkY/XR1iGIJh0FI/AAAAAAAAFEk/ynto7iWeqxkjhxH5UDMywUYHad3fFMHTACLcBGAs/s1600/carr2.png"); background-repeat: no-repeat; }
Result |
---|
Click here to move the object. |