title: Positioning jQuery dropdown menu so that it displays completely on the screen on a mobile device
body: <p>I have a basic jQuery dropdown menu and am testing it on mobile devices, specifically phones.</p>
  
  <p>One issue I've encountered is that submenus on the right side sometimes go off the edge of the screen, because the text in one or more of the items is too long. The user can, of course, scroll slightly to the right, but that's not a great solution. There is a similar question <a href="https://stackoverflow.com/questions/3087122/detect-if-a-web-drop-down-menu-is-going-to-display-off-screen">here</a>, but I couldn't get the proposed answers to work (plus I'm fumbling around since I'm still totally new to JS/jQuery).</p>
  
  <p>The general idea seems to be to get the left position+width of the current submenu (making sure they are shown first, then hide them again or show them and shift them when the user taps the menu) and see if that value is greater than the screen width. If it is, then it should be shifted to the left by the difference. However, my attempts don't seem to do anything to the elements and the menus keep appearing partially off-screen.  Currently, I have this (runs after the body loads):</p>
  
  <pre><code>var menus = $('#navbar').find('.subMenu');
  menus.show();
  menus.each(function(index) {
    var offsetMenu = $(this).offset();
    var diff = screen.width - ($(this).outerWidth + offsetMenu.left);
    if(diff &lt; 0) {
      $(this).offset({top:offsetMenu.top, left:offsetMenu + diff});
    }
    });
  menus.hide();
  </code></pre>
  
  <p>The jQuery version is 1.7.2 and the HTML structure is as follows (simplified version):</p>
  
  <pre><code>&lt;div id="navbar"&gt;
    &lt;ul&gt;
      &lt;li class="dropdown"&gt;&lt;a href="#"&gt;Link A&lt;/a&gt;&lt;/li&gt;
      &lt;li class="dropdown"&gt;&lt;a href="#"&gt;Link B&lt;/a&gt;
        &lt;ul class="subMenu"&gt;
          &lt;li&gt;&lt;a href="#"&gt;Link 1&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href="#"&gt;Link 2&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>How can I get this to work?</p>
  
  <p>Edit: Here's the relevant CSS, too.</p>
  
  <pre><code>#navbar ul.subMenu {
      position:absolute;
      display:none;
      background-color:#FFAF1E;
  }
  #navbar ul.subMenu li {
      clear:both;
  }
  #navbar a {
      text-decoration:none;
      color:#0C1F6E;
      display:block;
      padding-right:10px;
      padding-left:10px;
  }
  </code></pre>