Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Keypress Event Not Working For Simple Program

Hi everyone,

I have a simple image of a ball in my html div element and I would like it to move to the right, if I press the right arrow key. For some reason this is not working however. Help is much appreciated! :)

$(document).ready(function() {
  $("body").keydown(function(e){
    if(e.keyCode === 39) {
      $("div").animate({
      right: "+=300"
      });
    }
    else {alert("boo")};
  });

});

2 Answers

L B
L B
28,323 Points

If you want to move it to the right. You want to create space on its left. So, use left to move it to right. Change the 100 value to make it faster.

$(document).ready(function () {
    $("body").keydown(function (e) {
        if (e.keyCode === 39) {
            $("#item").animate({
                left: "+=50"
            }, 100, function () { //Speed of the movement. (Lower is faster)
            });
        } else {
            alert("boo")
        };
    });
});

Put your image inside a div with an id

    <div id="item"></div>

VERY IMPORTANT FOR THIS TO WORK: In your css styles. Put this as a style for the div that has the image.

#item {
    position: relative;
}

Awesome! Thank you L B! It didn't occur to me that I had to alter the CSS. Setting the position to relative did the trick.

Nick