0
$("html").keydown(function(event){

        if(event.which == "37")
            $("#hero").animate({"left" : "-=30px"});

        if(event.which == "39")
            $("#hero").animate({"left" : "+=30px"});

        if(event.which == "38")
            $("#hero").animate({"top" : "-=30px"});

        if(event.which == "40")
            $("#hero").animate({"top" : "+=30px"});
});

How can I enable #hero to move diagonally?

user1091856
  • 3,032
  • 6
  • 31
  • 42
  • be sure to use `keyup()` NOT `keydown()`. `keydown` acts weird in different browsers – Jason Feb 06 '12 at 22:50
  • keyup()???? But that's for when the key is released. #hero will only move when the key is released. – user1091856 Feb 06 '12 at 22:53
  • 1
    Check out [**my demo**](http://jsfiddle.net/bDMnX/7/) presented in [my answer here](http://stackoverflow.com/questions/4950575/how-to-move-a-div-with-arrow-keys/4951670#4951670). – Šime Vidas Feb 07 '12 at 00:05

2 Answers2

1

Edit: Check my updated DEMO

Reference: Can jQuery .keypress() detect more than one key at the same time?

Also check out the comment from Sime Vidas.. Nice animation.. His post: how to move a div with arrow keys

--- Old Post ---

Check my demo here..

The transition is not smooth and there are some issues.. I am trying to figure out why..

Community
  • 1
  • 1
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
0

The parameter to .animate() is a hash, so you can include more than one property. This would move #hero 30px up and 30px to the left:

$("#hero").animate({"left" : "-=30px", "top" : "-=30px"});
Thomas Kelley
  • 10,187
  • 1
  • 36
  • 43