Problem in animating with jquery

Hello Everyone, my code, for animating a div with arrow keys is not working.
here is the jquery code :

$(document).ready( function() {
    $(document).keydown(function(key) {
        switch(key) {
            case 37 : 
                $('.first').animate({left:'-=10'}, 0); 
                break; 
            case 38 : 
                $('.first').animate({left:'+=10'}, 0); 
                break; 
            case 39 : 
                $('.first').animate({top:'-=10'}, 0); 
                break;
            case 40 : 
                $('.first').animate({top:'+=10'}, 0); 
                break;
            default: 
                break; 
        }
    }); 
} ); 

and also the position in css is absolute. my problem is that my other jquery code is working, but this part of my code is not working at all.

and i tried to put the unit for animation. 10px , but still not working.

the discussion so far: http://www.dreamincode.net/forums/topic/394090-the-keys-dont-animate-the-div

The .keydown() callback gets the event passed as an argument, not (just) the keycode. Try

switch (key.which) {

instead.

1 Like

yeah, that worked. there is another problem! the original div does not move, a copy of it does !

Then we’d need to see more code. From that switch block alone it’s impossible to tell why this is happening.

alright, this is the css code :
.main { width: 100px; height: 100px; border-radius: 60px; background-color: green; margin: 10px; display: inline-flex; } .first { position: absolute; }
and this is the html :
`

`

and the jqery code is still the same.

I don’t know what you mean. You have three divs, and the one with the class .first is moving on keydown.

You mentioned other jQuery code in your OP though. Maybe there’s something wrong.

Edit: Since that div.first is absolutely positioned, it will initially be at the same position as the second, statically positioned div. Maybe that’s creating the impression of being a copy.

it’s fixed, somehow one div was on the otherone !

Would be fair to mention that on the other board too. ;-)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.