views:

178

answers:

2

I am working on an interface that requires that the user can click on a button, and then I will show a floating div positioned relative to the button (you can kind of think of it as the area that shows when you click the down arrow on a dropdown).

How can I correctly position this floating element adjacent to the button which was clicked (which could be anywhere on the page)?

Thanks in advance!!

+2  A: 

You can get the position of the button by using .offset()

For example:

$("#myButton").click(function() {
  var o = $(this).offset();
  $("#myDiv").css({'position': 'absolute','left':o.left,'top',o.top});
});

This would position it right on top of the button, just adjust that left/top wherever in relation you want it to go.

For example to place it below the button change the top portion to 'top': o.top + $(this).height() or to right right of the button: 'left':o.left + $(this).width()

Nick Craver
+1  A: 
<input type="button" id="btn" value="Choose Something" />

<div id="select">
  ...
</div>

with CSS:

#select { position: absolute; display: none; }

and Javascript:

$("#btn").click(function() {
  var sel = $("#select");
  var pos = $("#btn").offset();
  if (sel.is(":hidden")) {
    sel.attr({
      top: pos.top + 20,
      left: pos.left
    });
    sel.show();
  } else {
    sel.hide();
  }
});

Basically you absolutely position the floating div to remove it from the normal flow and then use offset() to figure out where to put it in relation to the button.

cletus