Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>tl;dr:</strong> (try it <a href="http://jsfiddle.net/wjbuys/QrrpB/" rel="noreferrer">here</a>)</p> <p>If you have the following HTML:</p> <pre><code>&lt;div id="menu" style="display: none;"&gt; &lt;!-- menu stuff in here --&gt; &lt;ul&gt;&lt;li&gt;Menu item&lt;/li&gt;&lt;/ul&gt; &lt;/div&gt; &lt;div class="parent"&gt;Hover over me to show the menu here&lt;/div&gt; </code></pre> <p>then you can use the following JavaScript code:</p> <pre><code>$(".parent").mouseover(function() { // .position() uses position relative to the offset parent, var pos = $(this).position(); // .outerWidth() takes into account border and padding. var width = $(this).outerWidth(); //show the menu directly over the placeholder $("#menu").css({ position: "absolute", top: pos.top + "px", left: (pos.left + width) + "px" }).show(); }); </code></pre> <p><strong>But it doesn't work!</strong></p> <p>This will work as long as the menu and the placeholder have the same offset parent. If they don't, and you don't have nested CSS rules that care where in the DOM the <code>#menu</code> element is, use:</p> <pre><code>$(this).append($("#menu")); </code></pre> <p>just before the line that positions the <code>#menu</code> element.</p> <p><strong>But it still doesn't work!</strong></p> <p>You might have some weird layout that doesn't work with this approach. In that case, just use <a href="http://jqueryui.com/demos/position/" rel="noreferrer">jQuery.ui's position plugin</a> (as mentioned in an <a href="https://stackoverflow.com/a/2781557/22107">answer</a> below), which handles every conceivable eventuality. Note that you'll have to <code>show()</code> the menu element before calling <code>position({...})</code>; the plugin can't position hidden elements.</p> <p><strong>Update notes 3 years later in 2012:</strong></p> <p>(The original solution is archived <a href="http://jsfiddle.net/wjbuys/LCt7z/" rel="noreferrer">here</a> for posterity)</p> <p>So, it turns out that the original method I had here was far from ideal. In particular, it would fail if:</p> <ul> <li>the menu's offset parent is not the placeholder's offset parent</li> <li>the placeholder has a border/padding</li> </ul> <p>Luckily, jQuery introduced methods (<code>position()</code> and <code>outerWidth()</code>) way back in 1.2.6 that make finding the right values in the latter case here a lot easier. For the former case, <code>append</code>ing the menu element to the placeholder works (but will break CSS rules based on nesting).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload