jQuery Events (filling out the cases)


#1


https://www.codecademy.com/courses/web-beginner-en-JwhI1/2/4?curriculum_id=50a3fad8c7a770b5fd0007a1

In super Mario exercise, I am trying to move the object (left, up, right, down) using the keyboard input codes (37, 38, 39, 40 (in order)).

Sometimes when I compile, the left and up work, and few seconds later when I try to compile again, they stop working, then they work again suddenly lol! (note: the code is the same, I don't change it).

However, meanwhile, the right and bottom never worked.

I tried to replace the key word (right) with left and (bottom) with top but still same results.


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


#2

Not exactly sure the reason for the problems you are facing, but for me the code works when case 39 and case 40 are written as follows:

// Right Arrow Pressed
case 39:
    $('img').animate({left: "+=10px"}, 'fast');
    break;

// Down Arrow Pressed
case 40:
    $('img').animate({top: "+=10px"}, 'fast');
    break;

#3

Thank you for replying, it's alright I changed the arrow keys to w (up), d (right), a (left), s (bottom) instead and it worked. I have not idea how or why the arrow input codes didn't function properly, but I did an alternative.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.