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.
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>
                        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;
    }
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With