jquery position changing with .css() behaving strange

Posted by 11684 on Stack Overflow See other posts from Stack Overflow or by 11684
Published on 2012-07-03T14:58:19Z Indexed on 2012/07/03 15:15 UTC
Read the original article Hit count: 154

Filed under:
|
|

I tried to make a moving img, and it works partially. If I press the right, up or down button, it moves right, up or down. But, if I press the left button, it jumps very fast very far to the right, and then back to the left and doesn't stop moving (I believe. I said it was fast).

JSFiddle;
Javascript:

$(document).ready(function() {
    var up = down = left = right = false;
    var top = 100, left = 500;
    $("body").on("keydown", function(e) {
        if(e.keyCode == 39) {e.preventDefault(); if (right == false) right = setInterval(moveRight, 80);}
        else if(e.keyCode == 37) {e.preventDefault(); if (left == false) left = setInterval(moveLeft, 80);}
        else if(e.keyCode == 38) {e.preventDefault(); if (up == false) up = setInterval(moveUp, 80);}
        else if(e.keyCode == 40) {e.preventDefault(); if (down == false) down = setInterval(moveDown, 80);}
    });
    $("body").on("keyup", function(e) {
        if(e.keyCode == 39) {clearInterval(right); right = false;}
        else if(e.keyCode == 37) {clearInterval(left); left = false;}
        else if(e.keyCode == 38) {clearInterval(up); up = false;}
        else if(e.keyCode == 40) {clearInterval(down); down = false;}
    });

    function moveUp() {
        top -= 2;
        $("#player").css("top", top + "px");
    }
    function moveDown() {
        top += 2;
        $("#player").css("top", top + "px");
    }
    function moveLeft() {
        left -= 2;
        $("#player").css("left", left + "px");
    }
    function moveRight() {
        left += 2;
        $("#player").css("left", left + "px");
    }
});

This is probably not the best way to do this, I'm open for better suggestions.

Thanks for reading!

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery