user1091856
user1091856

Reputation: 3158

(JQuery) Moving an element with key presses?

$("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"});
});

There seems to be a queue of all the keys that has been pressed, and I need this queue to be empty when the direction is changed. Because if I keep the left key pressed for a few seconds and then press right, the "#hero" will go left for a long time and then go right.

Upvotes: 0

Views: 1575

Answers (4)

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79850

Check my demo in which I use max of 2 key strokes for smooth transition.

Upvotes: 0

Jasper
Jasper

Reputation: 76003

If you don't queue the animations then you can let the element animate diagonally:

$("html").keydown(function(event){
    if(event.which == "37") $("#hero").animate({"left" : "-=30px"}, { queue : false });

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

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

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

Here is a demo: http://jsfiddle.net/x5Tn4/

Upvotes: 0

ShankarSangoli
ShankarSangoli

Reputation: 69915

You have to stop the current animation to avoid that. Try this.

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

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

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

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

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

.stop( [clearQueue] [, jumpToEnd] ) reference: http://api.jquery.com/stop/

clearQueue - Boolean indicating whether to remove queued animation as well. Defaults to false. jumpToEndA - Boolean indicating whether to complete the current animation immediately. Defaults to false.

Upvotes: 2

Z. Zlatev
Z. Zlatev

Reputation: 4820

$("#hero").stop().animate( ... );

Should be enough

Upvotes: 1

Related Questions