tl;dr: (try it here)
If you have the following HTML:
<div id="menu" style="display: none;">
<!-- menu stuff in here -->
<ul><li>Menu item</li></ul>
</div>
<div class="parent">Hover over me to show the menu here</div>
then you can use the following JavaScript 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();
});
But it doesn't work!
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 #menu
element is, use:
$(this).append($("#menu"));
just before the line that positions the #menu
element.
But it still doesn't work!
You might have some weird layout that doesn't work with this approach. In that case, just use jQuery.ui's position plugin (as mentioned in an answer below), which handles every conceivable eventuality. Note that you'll have to show()
the menu element before calling position({...})
; the plugin can't position hidden elements.
Update notes 3 years later in 2012:
(The original solution is archived here for posterity)
So, it turns out that the original method I had here was far from ideal. In particular, it would fail if:
- the menu's offset parent is not the placeholder's offset parent
- the placeholder has a border/padding
Luckily, jQuery introduced methods (position()
and outerWidth()
) way back in 1.2.6 that make finding the right values in the latter case here a lot easier. For the former case, append
ing the menu element to the placeholder works (but will break CSS rules based on nesting).