0

I know the objects can be animate in X and Y direction on the Page but can you please let me if it is possible to animate things in all directions like the YELLOW directions at below: enter image description here

so far I have a jquery code as:

 var position = $("#redBox").position();
    switch (e.keyCode)
    {
        case 37:
         $("#redBox").css('left',position.left - 2 +'px');
         break;
        case 38:
         $("#redBox").css('top',position.top - 2 +'px');
         break;
        case 39:
        $("#redBox").css('left',position.left + 2 +'px');
         break;
        case 40:
         $("#redBox").css('top',position.top + 2 +'px');
         break;
    }

which is moving the redBox in X and Y but how I can force it to move even in Yellow Lines on pushing the the KEYS (37+38) and (39+38)?

Thanks

Community
  • 1
  • 1
Behseini
  • 6,066
  • 23
  • 78
  • 125
  • You could look here for how to capture multiple key events: http://stackoverflow.com/questions/5203407/javascript-multiple-keys-pressed-at-once – Mathias Mar 06 '14 at 17:20
  • Thanks Mathias, but I do not know how to use the keys in the switch statement! – Behseini Mar 06 '14 at 17:25

2 Answers2

0

If you want to move up + left just do both.

$("#redBox").css({ 'left': position.left - 2 + 'px', 'top': position.top + 2 + 'px'});

Or with animation like here: http://jsfiddle.net/jdWRT/

PS.

I stole the link from here: How to move an element in Diagonal Movement in jQuery?

Community
  • 1
  • 1
bobek
  • 8,003
  • 8
  • 39
  • 75
  • Thanks bobek, but how can I use the Keys here? – Behseini Mar 06 '14 at 17:20
  • Just keep track of the keys that were pressed down. Add them to array and clean the array up when needed. Look here :http://stackoverflow.com/questions/5203407/javascript-multiple-keys-pressed-at-once – bobek Mar 06 '14 at 17:22
  • well it is kind of confusing for me! so how can I have Case 39 and 38 together in the switch statement? – Behseini Mar 06 '14 at 17:24
0

When an arrow key is pressed down (onkeydown), you can set a flag for that key. When that key is let go (onkeyup), you can unset that flag. That way you'll always know the state of each key and you can test if any combination of keys is pressed in your onkeydown handler (or anywhere else).

At that point you just have to do what bobek said and adjust both the left and top properties at the same time.

  • Also, if you're planning to animate this I would recommend using plain javascript instead of jQuery. While jQuery can make things very quick to code, it's painfully slow and you'll notice when you start doing lots of method calls each second. – user3389167 Mar 06 '14 at 17:35