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!!
<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.