keydown()
methodYou 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">
<head>
<meta charset="utf-8">
<title>jQuery Move DIV Element with Arrow Keys</title>
<style>
.box{
width: 100px;
height: 100px;
position: relative;
margin: 200px auto 0;
background: 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><strong>Note:</strong> Click inside the viewport and press the arrow keys to move the box.</p>
<div class="box"></div>
</body>
</html>
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 [email protected]
Upload Single and Multiple Images with Preview in React with Example
Today in this React image upload preview...Laravel 8 - User Roles and Permissions using Spatie
nowaday our leading subject is laravel 8...Laravel 5.5 - Razorpay Payment Gateway Integration
Today, we are share with you in this tut...How to compare two strings in PHP
Use the PHP strcmp() function...Laravel 8 - Ajax CRUD With yajra Datatable and Bootstrap Model Validation Example
In this article, I will share with your...