Reputation: 345
I wanted to make an element move on arrow press by applying .css() but its not working at all and I cant figure out why. The exactly same code is working perfectly with JQ animate(). Can you explain me why the .css is not working ? I know there are better ways to do this but I'm just curious why its not attaching the top property.Below is the code with animate
$(document).ready(function(){
$('body').keydown(function() {
if (event.which == 38)
{
$('div').animate({top:'-=10px'},'fast');
}
else if (event.which == 40)
{
$('div').animate({top:'+=10px'},'fast');
}
else if (event.which == 37)
{
$('div').animate({left:'-=10px'},'fast');
}
else if (event.which == 39)
{
$('div').animate({left:'+=10px'},'fast');
}
});
});
Upvotes: 4
Views: 1839
Reputation: 32192
Using .css()
to adjust a property requires that property to be explicitly set beforehand, whereas .animate()
will adjust the calculated position of an element without it being specifically set.
In the below snippet, I have given the #movable
element top
and left
properties, and left the other <div>
without them. The selector that .css()
is applied to affects both <divs>
, but note that only the <div>
with the top
and left
properties moves.
$(document).ready(function(){
$('body').keydown(function(event) {
if (event.which == 38)
{
$('div').css({top:'-=10px'});
}
else if (event.which == 40)
{
$('div').css({top:'+=10px'});
}
else if (event.which == 37)
{
$('div').css({left:'-=10px'});
}
else if (event.which == 39)
{
$('div').css({left:'+=10px'});
}
//added to stop Stack Overflow scrolling
event.preventDefault();
});
});
div {
position:relative;
}
/* Set top and left of the movable div explicitly */
#movable {
top:0px;
left:0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="movable">movable</div>
<div>immovable</div>
Upvotes: 2
Reputation: 7117
Moving div
require space to move or you can use position:absolute
Demo
Upvotes: 2
Reputation: 22933
Is the code in the post your real code? Because you're using an event
variable, but you haven't defined any argument to the function passed to keydown
. It needs to be $('body').keydown(function(event) {
.
Upvotes: 1