10 using keydown


#1

not sure why not pass this code like this

$(document).ready(function(){
$('img').keydown(function(key){});    

});

#2

Hi Brian,

That's most likely because if you listen for keydown()s on document, the user can click anywhere within the page, then press a key, and the image will move. If you listen for keydown()s on the image however, you need to click the image first.
That's just some info on how it works, though. I don't know why the course author chose to make you listen for the event on the document.


#3

Keyboard events are usually bound to focusable elements, such as form controls, in absence of which we can bind to the document object, which will then delegate the event handler. They can be bound to any element, but as @zystvan states above, they won't trigger until that element has focus (such as a click on the element).

$(document).keydown(function(){
    $('img').animate({left: '+=10px'}, 'slow');
});

We may click anywhere in the window to give it focus, then a keydown event will trigger the handler to move the image 10 pixels to the right.