title: How do I make an object stop if it reaches a certain point on a page?
body: <p>I am making a game where you can move around in a certain area but the problem is that you can move freely outside the area I want the player to be in. Is there any way I can make it so that if the player reaches a certain coordinate on the page that he cant move any further?</p>
  
  <p>I coded it so that everytime any of the arrow keys are pressed the player moves 16px to the direction chosen.</p>
  
  <pre><code>&lt;script&gt;
  //pressing a key
  $(document).keydown(function(e){
  
  //sets variables
  var position = $("#player").position();
  var xLimit = 500;
  var yLimit = 300;
  var currentX = 0;
  var currentY = 0;
  var offset = 16;
  
  //everytime user presses "left" key object "player" moves left 16 pixels.
  switch(e.keyCode){
  case 37: //left
  $("#player").css('left', position.left - 16 + 'px');
  
  function moveLeft() {
     if (currentX + offset &lt;= xLimit) {
         currentX += offset;
     }
  }
  break;
  
  
  //everytime user presses "up" key object "player" moves up 16 pixels.
  case 38: //up
  $("#player").css('top', position.top - 16 + 'px');
  
  function moveUp() {
     if (currentX + offset &lt;= xLimit) {
         currentX += offset;
     }
  }
  break;
  
  
  //everytime user presses "right" key object "player" moves right 16 pixels.
  case 39: //right
  $("#player").css('left', position.left + 16 + 'px');
  
  function moveRight() {
     if (currentX + offset &lt;= xLimit) {
         currentX += offset;
     }
  }
  break;
  
  
  //everytime user presses "down" key object "player" moves down 16 pixels.
  case 40: //down
  $("#player").css('top', position.top + 16 + 'px');
  break;
  
  function moveDown() {
     if (currentX + offset &lt;= xLimit) {
         currentX += offset;
     }
  }
  
  }
  });
  &lt;/script&gt;
  </code></pre>
  
  <p>I tried it but did not work, any suggestions?</p>