What parseInt(key.which,10) do in (line 3)


#1
 $(document).ready(function() {
    $(document).keydown(function(key) {
        switch(parseInt(key.which,10)) {
            // Left arrow key pressed
            case 37:
                $('img').animate({left: "-=10px"}, 'fast');
                break;
            // Up Arrow Pressed
            case 38:
                // Put our code here
                    $('img').animate({top: "-=10px"},'fast');
                break;
            // Right Arrow Pressed
            case 39:
                $('img').animate({left: "+=10px"},'fast');
                // Put our code here
                break;
            // Down Arrow Pressed
            case 40:
                $('img').animate({top: "+=10px"},'fast');
                // Put our code here
                break;
        }
    });
});

and why there is no right and down function only 2 things work is top and left


#2

The reason there's no right / down directions for movement in jQuery is because all web based programs run on a 2D frame. Basically X = left || Y = top. If you've taken basic Algebra, you can relate it to a graph, it has two ways to define position, on the X and Y axis. If it were 3D you'd be looking at "Depth" as well.

But more specifically, it's because you can move up, down, left, and right, without having a right, or down, option.

Also, you need to take into account that 0,0 on the XY axis is not in the middle of the screen, 0X, and 0Y start in the top left corner of the window, and going negative in any of these will take the object you're moving off of the screen.

Another questions you may have is "then how do I know how big the window is going to be?" good question! that's one that's a struggle because users can change how big their browsers are based on how big their screens are, and how big or small they want their internet window to be. There are ways around this but you'll learn about those in later lessons.


#3

can anyone shed light on what is happening with the '(parseInt(key.which,10))'?

I've used parseInt for calculations before but I'm kind of confused as to what specifically is happening here. any help is appreciated.


#4

Hi Schrode,

http://www.w3schools.com/jsref/jsref_parseint.asp

parseInt has the following syntax: parseInt(string, radix). String is the string to be parsed (required), and radix is an optional number (from 2 to 36) that represents the numeral system to be used (like 10 for decimal). I hope that this answers your question.

Martin