jQuery event.which move an element to left/right/up/down with arrow keys

Description

jQuery event.which move an element to left/right/up/down with arrow keys

View in separate window

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Move an Element to Left/Right/Up/Down Using Arrow Keys</title>
<style>
    .box{//  www. j ava2 s.c o  m
        width: 100px;
        height: 100px;
        position: relative;
        margin: 200px auto 0;
        background: url("image1.png") yellowgreen;
    }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(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>Click inside the output viewport and press the arrow keys to move the box.</p>
    <div class="box"></div>
</body>
</html>



PreviousNext

Related