jQuery Moving Elements using Keys | Lessoncup Programming Blog

Wednesday, 23 March 2016

jQuery Moving Elements using Keys

Hi, today i am going to tell you about how to move elements using keys like Left, Right, Up and Down, in my previous lessons we have seen about jQuery Keyboard Events use keydown function and assign to document, you can use if condition or switch, i just write it in if condition here the logic is simple first we need to capture the left right up and down key codes, we can use keyCode method to capture the key codes see the code bellow


take one element in html page and give it name as #box now we need to assign four if conditions and in each condition just put the condition like if(event.keyCode==37) like this way get the for arrow key codes and put it in if conditions and write the statement, in the statement just use the animate() method to move elements

jQuery


<script type="text/javascript" src="jquery-1.10.2.min.js"></script>

<script>

$(document).ready(function(){

$(document).keydown(function(event){
 
 
 if(event.keyCode==37){
 
 $('#box').animate({left:"-=20"}).css({"transform": "rotate(270deg)"});
 
 $('.msg').html("You pressed Left Arrow Kye. event code is "+event.keyCode);
 
 
 }
 
 if(event.keyCode==39){
 
 $('#box').animate({left:"+=20"}).css({"transform": "rotate(90deg)"});
 $('.msg').html("You pressed Right Arrow Kye. event code is "+event.keyCode);
 
 }
 
 if(event.keyCode==38){
 
 $('#box').animate({top:"-=20"}).css({"transform": "rotate(0deg)"});
 $('.msg').html("You pressed Up Arrow Kye. event code is "+event.keyCode);
 
 }
 
 if(event.keyCode==40){
 
 $('#box').animate({top:"+=20"}).css({"transform": "rotate(180deg)"});
 $('.msg').html("You pressed Down Arrow Kye. event code is "+event.keyCode);
 
 }

  
});


});
</script>


Live Demo   Download Script

No comments :

Post a Comment

Mohammad Khasim
Blogger | Web Developer
Hyderabad - INDIA
lessoncup@gmail.com

PHP | My SQL | JQUERY
Web Development Tools | CMS | Frameworks | SEO

Get my Latest Lessons