Reputation: 1433
I have a div which i am trying to animate using jQuery.My goal is to move the div left,up,right and down based on the corresponding key presses.
E.g if i press the left arrow key, the div moves left etc etc.
Currently my div is able to move, left,right,up and down when then page loads/refreshes. HOWEVER, once i move my div right i am unable to move it left, when i move it down, i am unable to move it up and so on...
How would i make my div more smoothly in all directions?
jsfiddle:http://jsfiddle.net/6U6cA/4/
My code
HTML:
<body>
<div id="container">
<div id="switcher">
<div class="label">TestDiv</div>
<button id="switcher-default">Default</button>
<button id="switcher-large">Default 1</button>
<button id="switcher-small">Default 2</button>
</div>
</div>
</body>
CSS:
#switcher {
width: 300px;
padding: .5em;
border: 1px solid #777;
}
.label {
width: 130px;
margin: .5em 0;
cursor: pointer;
}
jQuery:
$(document).ready(function() {
$('#switcher').css({
position:'relative',
display:'inline-block'
});
$(document).keyup(function(event){
var key=event.which;
switch(key){
case 37:
$('#switcher').animate({right:'+=20'});
break;
case 38:
$('#switcher').animate({bottom:'+=20'});
break;
case 39:
$('#switcher').animate({left:'+=20'});
break;
case 40:
$('#switcher').animate({top:'+=20'});
break;
}
});
Upvotes: 1
Views: 134
Reputation: 318302
You're first setting the left
style property, and then the right
, but that doesn't work because left
is not removed so it's overriding the right
style.
Stick with one CSS property
$(document).ready(function () {
$('#switcher').css({
position: 'relative',
display: 'inline-block'
});
$(document).keyup(function (event) {
var key = event.which;
switch (key) {
case 37:
$('#switcher').animate({
left: '-=20'
});
break;
case 38:
$('#switcher').animate({
top: '-=20'
});
break;
case 39:
$('#switcher').animate({
left: '+=20'
});
break;
case 40:
$('#switcher').animate({
top: '+=20'
});
break;
}
});
});
Upvotes: 2