How to position one element relative to another with jQuery? -


i have hidden div contains toolbar-like menu.

i have number of divs enabled show menu div when mouse hovers on them.

is there built-in function move menu div top right of active (mouse hover) div? i'm looking $(menu).position("topright", targetel);

tl;dr: (try here)

if have following html:

<div id="menu" style="display: none;">    <!-- menu stuff in here -->    <ul><li>menu item</li></ul> </div>  <div class="parent">hover on me show menu here</div> 

then can use following javascript code:

$(".parent").mouseover(function() {     // .position() uses position relative offset parent,      var pos = $(this).position();      // .outerwidth() takes account border , padding.     var width = $(this).outerwidth();      //show menu directly on placeholder     $("#menu").css({         position: "absolute",         top: pos.top + "px",         left: (pos.left + width) + "px"     }).show(); }); 

but doesn't work!

this work long menu , placeholder have same offset parent. if don't, , don't have nested css rules care in dom #menu element is, use:

$(this).append($("#menu")); 

just before line positions #menu element.

but still doesn't work!

you might have weird layout doesn't work approach. in case, use jquery.ui's position plugin (as mentioned in answer below), handles every conceivable eventuality. note you'll have show() menu element before calling position({...}); plugin can't position hidden elements.

update notes 3 years later in 2012:

(the original solution archived here posterity)

so, turns out original method had here far ideal. in particular, fail if:

  • the menu's offset parent not placeholder's offset parent
  • the placeholder has border/padding

luckily, jquery introduced methods (position() , outerwidth()) way in 1.2.6 make finding right values in latter case here lot easier. former case, appending menu element placeholder works (but break css rules based on nesting).


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -