title: How to prevent image from going out of the window with JQuery
body: <p>I'm trying to make a simple image move on the screen with the arrow keys up, down, left and right. It works fine except that the image keeps going out of the window and I can't see. What I want to do is keep the image within the window bounds and not go out of it.</p>
  
  <p>Here's my code:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>let height = $(window).height();
  let width = $(window).width();
  
  $(document).keydown(function(key) {
    switch (parseInt(key.which, 10)) {
      // Left arrow key pressed
      case 37:
        if ($('img').position().left &gt; 0) {
          $('img').animate({
            left: "-=20px"
          }, 'fast');
        }
        break;
        // Up Arrow Pressed
      case 38:
        if ($('img').position().top &gt; 0) {
          $('img').animate({
            top: '-=20px'
          }, 'fast');
        }
        break;
        // Right Arrow Pressed
      case 39:
        if ($('img').position().left &lt; width) {
          $('img').animate({
            left: '+=20px'
          }, 'fast');
        }
        break;
        // Down Arrow Pressed
      case 40:
        if ($('img').position().top &lt; height) {
          $('img').animate({
            top: '+=20px'
          }, 'fast');
        }
        break;
    }
  });</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    width: 100%;
    height: 100%;
    background: blue;
    overflow: hidden;
    /*This is the solution*/
  }
  
  img {
    position: relative;
    left: 0;
    top: 0;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;img src="http://pngimg.com/uploads/mario/mario_PNG129.png" /&gt;</code></pre>
  </div>
  </div>
  </p>