Ad

Can Not Use JQuery Keycode To Change Element's CSS

- 1 answer

I'm following a tutorial on making a character move around the screen using html, css and jquery. I am not sure why the arrow keys are not making the character move. When I press the left, up, right, or down keys, the only thing that happens is the scroll bar on the left and bottom moves. What's wrong??

$(function() {
  var player = '<div id="player"></div>';
  $("#map").append(player);


  $(document).keydown(function(e) {
    //alert(e.keyCode);

    var position = $("#player").position();


    switch (e.keycode) {
      case 37: //left
        $("#player").css('left', position.left - 20 + 'px');
        break;

      case 38: //up
        $("#player").css('top', position.top - 20 + 'px');
        break;

      case 39: //right
        $("#player").css('left', position.left + 20 + 'px');
        break;

      case 40: //down
        $("#player").css('top', position.top + +'px');
        break;

    }
  });

});
#player {
  position: absolute;
  background: url("http://tse1.mm.bing.net/th?&id=OIP.M0268adc5eb05ad8612f14346c852f3dbo0&w=121&h=186&c=0&pid=1.9&rs=0&p=0&r=0") no-repeat;
  width: 165px;
  height: 175px;
}
#map {
  position: relative;
  border: 1px solid black;
  height: 600px;
  width: 800px;
}
<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <link rel="stylesheet" target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="maze.css" />
</head>

<body>
  <h1>Maze</h1>


  <div id="map"></div>
  <div id="output"></div>


</body>

</html>

Ad

Answer

Javascript is case sensitive.

//e.keycode is wrong
switch (e.keycode) {
    //blah
}

//e.keyCode is correct
switch (e.keyCode) {
    //blah
}

and there is missing operand error too,

// Wrong
$("#player").css('top', position.top + +'px');
// Correct
$("#player").css('top', position.top + 20 +'px');

Fiddle

Ad
source: stackoverflow.com
Ad