11. Why does my code not work?


#1

Here is what I wrote:

$(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:
$('img').animate({top: "-=10px"}, 'fast');
// Put our code here
break;
// Right Arrow Pressed
case 39:
// Put our code here
$('img').animate({left: "+=10px"}, 'fast');
break;
// Down Arrow Pressed
case 40:
// Put our code here
$('img').animate({top: "+=10px"}, 'fast');
break;
}
});
});

I don't understand why it doesn't work. Can anyone help please? Thank you!


#2

It works for me. Before I try to move the image, I always use the mouse and click on the image before trying to move it with the keyboard


#3

I found the code you need to use:

$(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:
				$('img').animate({top: "-=10px"}, "fast");
				break;
			// Right Arrow Pressed
			case 39:
				$('img').animate({left: "+=10px"}, 'fast');
				break;
			// Down Arrow Pressed
			case 40:
				$('img').animate({top: "+=10px"}, 'fast');
				break;
		}
	});
});

#4

Why do yours work & there's dnt? Thanks BTW :smile:


#5

Thanks @steve80. I did what you suggest, and it works for me


#6

@steve80,
=clicking on the document= is called putting the document on-focus


#7

I see. Hopefully, I would get used to the technical terms. Thanks for the tip


#8

@steve80,
on focus site:jquery.com
https://api.jquery.com/focus/
https://api.jquery.com/focusin/


#10

Problem that occurs is that program won't let you pass if you don't use words up, down, left, right in your cases. Doesn't matter the order I wrote here.