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

  118 views   2 months ago jQuery

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. Let's check out an example to see how this works:

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>jQuery Move DIV Element with Arrow Keys</title>
        width: 100px;
        height: 100px;
        position: relative;
        margin: 200px auto 0;
        background: yellowgreen;
<script src=""></script>
    switch (e.which){
    case 37:    //left arrow key
            left: "-=50"
    case 38:    //up arrow key
            top: "-=50"
    case 39:    //right arrow key
            left: "+=50"
    case 40:    //bottom arrow key
            top: "+=50"
    <p><strong>Note:</strong> Click inside the viewport and press the arrow keys to move the box.</p>
    <div class="box"></div>


Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on

Related Articles