Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .animate() not working

I am new to jQuery and have been learning it through Codecademy. I am creating a 'codebit' (website) on the site, and I am trying to make an image sprite react (move) when the up, down, left and right keys are pressed.

HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>Sprite</title>
        <link rel='stylesheet' type='text/css' href='style.css'/>
        <script type='text/javascript' src='script.js'></script>
    </head>
    <body>
        <img src="[img]"/>
    </body>
</html>

CSS:

img {
    position: relative;
    left: 0;
    top: 0;
}

Javascript:

$(document).ready(function() {
    $(document).keydown(function(key) {
        switch(parseInt(key.which,10)) {
            //LEFT
            case 37:
                $('img').animate({left: "-=10px"}, 500);
                break;
            //RIGHT
            case 39:
                $('img').animate({left: "+=10px"}, 500);
                break;
            //UP
            case 38:
                $('img').animate({top: "-=10px"}, 500);
                break;
            //DOWN
            case 40:
                $('img').animate({top: "+=10px"}, 500);
                break;
        }
    });
});

I have checked on a few sites for syntax errors, and can't seem to find any obvious ones. Help would be most appreciated.

like image 732
gilbert-v Avatar asked Dec 08 '22 08:12

gilbert-v


2 Answers

You should include the jQuery-script in your head (before your own script.js).

Like

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
like image 102
Peter van der Wal Avatar answered Dec 11 '22 11:12

Peter van der Wal


Here's a quick version.

http://jsfiddle.net/E45hb/

JS

$(document).keydown(function (key) {
    switch (parseInt(key.which, 10)) {
        case 37:
            $('img').stop(true).animate({
                left: "-=10px"
            }, 'fast');
            break;
        case 38:
            $('img').stop(true).animate({
                top: "-=10px"
            }, 'fast');
            break;
        case 39:
            $('img').stop(true).animate({
                left: "+=10px"
            }, 'fast');
            break;
        case 40:
            $('img').stop(true).animate({
                top: "+=10px"
            }, 'fast');
            break;
    }
});
like image 44
MarioD Avatar answered Dec 11 '22 09:12

MarioD