title: Prevent menu to show outside window
body: <p>I am using a <code>ul</code> as a contextual menu in a php-file-listing application.</p>
  
  <p>I recently added this piece of code to move the menu when the cursor is too close from the borders of the window, in order to prevent the menu to be drawn partially outside of the window.</p>
  
  <pre><code>if ((PosY + elm.outerHeight()) &gt; $(window).height()) {
    PosY = PosY - elm.outerHeight();
  }
  if ((PosX + elm.outerWidth()) &gt; $(window).width()) {
    PosX = PosX - elm.outerWidth();
  }
  </code></pre>
  
  <p>But…<br>
  <strong>Sometimes</strong> the code works, and the menu is moved,<br>
  And <strong>sometimes</strong> it doesn't work, and the menu is displayed as below:<br>
  (Let's say it doesn't work like 1 out of 5 times)</p>
  
  <p><a href="https://i.stack.imgur.com/MFUCB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MFUCB.png" alt="Menu is outside !"></a></p>
  
  <p>I tried consoling the variables but they seem to be correct and I really don't understand why it is happening.  </p>
  
  <p>Here is a working snippet, where I managed to reproduce the problem.<br>
  (As it is an extract of my code, much of the CSS is missing but that's not important.)</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>// Global vars
  var PosX = 0;
  var PosY = 0;
  
  // Mouse mouve
  $(document).mousemove(function(e) {
    PosX = e.pageX;
    PosY = e.pageY;
    return;
  });
  
  /*
   CONTEXT MENU
  */
  // Trigger action when the contexmenu is about to be shown
  $(document).on("contextmenu", function(event) {
    // Avoid the regular one
    event.preventDefault();
  });
  // If the document is clicked somewhere
  $(document).on("mousedown", function(e) {
    // If the clicked element is not the menu
    if ($(e.target).parents(".ContextMenu").length == 0) {
      // Hide it
      $(".ContextMenu").fadeOut(100);
    }
  });
  
  // On context menu…
  function ContextMenu(id) {
  
    elm = $("#" + id);
  
    /*
    console.log("PosY:", PosY);
    console.log("elm H:", elm.outerHeight());
    console.log("win H:", $(window).height());
   
    console.log("PosX:", PosX);
    console.log("elm W:", elm.outerWidth());
    console.log("win W:", $(window).width());
    */
  
    // Moves menu if out of screen
    if ((PosY + elm.outerHeight()) &gt; $(window).height()) {
      PosY = PosY - elm.outerHeight();
    }
    if ((PosX + elm.outerWidth()) &gt; $(window).width()) {
      PosX = PosX - elm.outerWidth();
    }
  
    // Hide and reopen the menu required
    elm.fadeOut(100, function() {
      elm.css({
        "top": PosY,
        "left": PosX
      }).fadeIn(200);
    });
    //console.log("Context menu on: " + elm);
    return false;
  }</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>@charset "UTF-8";
  
  * {
    margin: 0;
    padding: 0;
  }
  
  body {
    font-size: 16px;
    position: fixed;
    color: #000;
  }
  
  p,
  input,
  label,
  button,
  a {
    font-family: "Source Sans Pro", "Trebuchet MS", Helvetica, sans-serif;
    display: inline-block;
    cursor: inherit;
  }
  
  #InTable {
    table-layout: fixed;
    width: 100%;
    border: 0;
    border-collapse: collapse;
    margin-bottom: 800px;
  }
  
  
  /* Scrollbar */
  
  #Table::-webkit-scrollbar-track-piece {
    background-color: #DDD;
  }
  
  #Table::-webkit-scrollbar-thumb {
    background-color: #000;
  }
  
  thead th {
    padding: 4px 0;
  }
  
  thead th i {
    margin-left: 4px;
    font-size: 14px !important;
    color: #CCC;
  }
  
  thead th,
  tbody tr {
    cursor: pointer;
  }
  
  tbody td {
    vertical-align: middle;
  }
  
  tbody td:first-of-type {
    margin: 0 auto;
    /*overflow: hidden; */
  }
  
  tbody td img {
    vertical-align: middle;
    height: 32px;
  }
  
  tbody tr:nth-of-type(odd) td {
    background-color: #EEEEEE;
  }
  
  tbody tr:nth-of-type(even) td {
    background-color: #DDDDDD;
  }
  
  #Table th,
  #Table td {
    position: relative;
  }
  
  #Table p {
    padding-left: 4px;
  }
  
  .ContextMenu {
    position: fixed;
    display: none;
    background: #f8f8f8;
    border: 2px solid #888;
    z-index: 2;
    color: #333;
    /* Smoothy color */
  }
  
  .ContextMenu div {
    background: #e8e8e8;
    height: 16px;
    padding: 4px;
    border-bottom: 1px solid #CCC;
  }
  
  .ContextMenu div:not(:first-child) {
    border-top: 2px solid #AAA;
  }
  
  .ContextMenu li {
    display: block;
    height: 20px;
    padding: 6px 24px 6px 8px;
    cursor: pointer;
    list-style-type: none;
    transition: all .3s ease;
    white-space: nowrap;
  }
  
  .ContextMenu img,
  .ContextMenu i,
  .ContextMenu span,
  .ContextMenu p {
    display: inline-block;
    height: 20px;
    vertical-align: middle;
  }
  
  .ContextMenu img,
  .ContextMenu i,
  .ContextMenu span {
    width: 20px;
    text-align: center;
    margin-right: 8px;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;style media="" data-href="https://use.fontawesome.com/releases/v5.0.6/css/all.css"&gt;&lt;/style&gt;
  
  &lt;body class="tblr0 bg" id="DropBox" contenttype="text/html; charset=UTF-8" onload="" onresize=""&gt;
    &lt;div class="abs t40blr0" id="Content" style="top: 100px;"&gt;
      &lt;div class="abs tblr0 overflow-x-hidden overflow-y-auto" id="Table" style="opacity: 1;"&gt;
        &lt;table class="tblr0" id="InTable"&gt;
          &lt;thead class="bg-silver align-l"&gt;
            &lt;tr style="width: 100%;"&gt;
              &lt;th data-sort="int" id="Icos" style="width: 68px; min-width: 68px; max-width: 68px;"&gt;&lt;p&gt;Icon&lt;/p&gt;&lt;i class="fa fa-sort"&gt;&lt;/i&gt;&lt;/th&gt;
              &lt;th data-sort="string" id="Name" style="width: 291.333px;"&gt;
                &lt;p&gt;Filename&lt;/p&gt;&lt;i class="fa fa-sort"&gt;&lt;/i&gt;&lt;/th&gt;
              &lt;th data-sort="string" id="Type" style="width: 218.5px;"&gt;
                &lt;p&gt;Type&lt;/p&gt;&lt;i class="fa fa-sort"&gt;&lt;/i&gt;&lt;/th&gt;
            &lt;/tr&gt;
          &lt;/thead&gt;
          &lt;tbody&gt;
            &lt;tr onclick="" oncontextmenu="ContextMenu('ContextMenu0');" style="width: 100%;"&gt;
              &lt;td data-sort-value="0" style="height: 64px;"&gt;
                &lt;div class="Icons" style="line-height: 64px; font-size: 60px;"&gt;&lt;/div&gt;
              &lt;/td&gt;
              &lt;td style="height: 64px;"&gt;
                &lt;div class="Name"&gt;
                  &lt;p&gt;.&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;i&gt;[Current]&lt;/i&gt;&lt;/p&gt;
                &lt;/div&gt;
              &lt;/td&gt;
              &lt;td style="height: 64px;"&gt;
                &lt;p&gt;&amp;lt; Current Directory&amp;nbsp;&amp;gt;&lt;/p&gt;
              &lt;/td&gt;
              &lt;td style="height: 64px;"&gt;
                &lt;ul class="ContextMenu" id="ContextMenu0"&gt;
                  &lt;div onclick="context_menu_close(event);"&gt;
                    &lt;p&gt;Tools&lt;/p&gt;
                  &lt;/div&gt;
                  &lt;li onclick=""&gt;&lt;i class="fa fa-folder"&gt;&lt;/i&gt;
                    &lt;p&gt;Create new Folder&lt;/p&gt;
                  &lt;/li&gt;
                  &lt;li onclick=""&gt;&lt;i class="fa fa-file"&gt;&lt;/i&gt;
                    &lt;p&gt;Create new File&lt;/p&gt;
                  &lt;/li&gt;
                  &lt;li onclick=""&gt;&lt;i class="fa fa-upload"&gt;&lt;/i&gt;
                    &lt;p&gt;Upload files in current folder&lt;/p&gt;
                  &lt;/li&gt;
                  &lt;li onclick=""&gt;&lt;i class="fa fa-download"&gt;&lt;/i&gt;
                    &lt;p&gt;Download current folder as Zip&lt;/p&gt;
                  &lt;/li&gt;
                &lt;/ul&gt;
              &lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr onclick="" oncontextmenu="ContextMenu('ContextMenu1');" style="width: 100%;"&gt;
              &lt;td data-sort-value="1" style="height: 64px;"&gt;
                &lt;div class="Icons" style="line-height: 64px; font-size: 60px;"&gt;&lt;/div&gt;
              &lt;/td&gt;
              &lt;td style="height: 64px;"&gt;
                &lt;div class="Name pr4"&gt;
                  &lt;p&gt;Acces&lt;span class="opac06"&gt;&amp;nbsp;&lt;/span&gt;&lt;/p&gt;
                &lt;/div&gt;
              &lt;/td&gt;
              &lt;td style="height: 64px;"&gt;
                &lt;p&gt;&amp;lt;&amp;nbsp;Directory&amp;nbsp;&amp;gt;&lt;/p&gt;
              &lt;/td&gt;
              &lt;td style="height: 64px;"&gt;
                &lt;ul class="ContextMenu" id="ContextMenu1" style="top: 218px; left: 854.625px; display: none;"&gt;
                  &lt;div onclick="context_menu_close(event);"&gt;
                    &lt;p&gt;Tools&lt;/p&gt;
                  &lt;/div&gt;
                  &lt;li onclick=""&gt;&lt;i class="fa fa-i-cursor"&gt;&lt;/i&gt;
                    &lt;p&gt;Rename&lt;/p&gt;
                  &lt;/li&gt;
                  &lt;li onclick=""&gt;&lt;i class="far fa-arrow-alt-circle-right"&gt;&lt;/i&gt;
                    &lt;p&gt;Move&lt;/p&gt;
                  &lt;/li&gt;
                  &lt;li onclick=""&gt;&lt;i class="far fa-copy"&gt;&lt;/i&gt;
                    &lt;p&gt;Copy&lt;/p&gt;
                  &lt;/li&gt;
                  &lt;li onclick=""&gt;&lt;i class="far fa-trash-alt"&gt;&lt;/i&gt;
                    &lt;p&gt;Delete&lt;/p&gt;
                  &lt;/li&gt;
                  &lt;li onclick=""&gt;&lt;i class="fa fa-download"&gt;&lt;/i&gt;
                    &lt;p&gt;Download folder as Zip&lt;/p&gt;
                  &lt;/li&gt;
                &lt;/ul&gt;
              &lt;/td&gt;
            &lt;/tr&gt;
          &lt;/tbody&gt;
        &lt;/table&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/body&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>Can someone enlighten me?<br>
  What is wrong with my code?<br>
  Thanks in advance.</p>