Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to position a div at the top of another div with javascript?

The first div is the '#icon-selection-menu' bar, it's idle position is absolute with top:0px and left:0px. So it appears at he top left corner inside the content div.

Deep in the content div children I got other divs which are actually kind of '.emoticon-button'. Their position is relative inside their parent. On such button click I'd like to position the first div just above the button, adjusting it's bottom border to the button's top border.

How can I get top and left values to set $('#icon-selection-menu').top and $('#icon-selection-menu').left ?

like image 531
zuba Avatar asked Feb 27 '13 04:02

zuba


People also ask

How do I bring a div in front of another div?

Use the CSS z-index property. Elements with a greater z-index value are positioned in front of elements with smaller z-index values. Note that for this to work, you also need to set a position style ( position:absolute , position:relative , or position:fixed ) on both/all of the elements you want to order.

How do I bring a div to the top?

In order to pull an html element out of the natural flow of how the elements are layed out on the screen you need to use position: absolute. This will allow the element to become a layer above the other elements (assuming that the z-index value is greater than all other's).


1 Answers

jQuery1 provides .offset() to get the position of any element relative to the document. Since #icon-selection-menu is already positioned relative to the document, you can use this:

var destination = $('.emoticon-button').offset();
$('#icon-selection-menu').css({top: destination.top, left: destination.left});

$('#icon-selection-menu') will be placed at the top-left corner of $('.emoticon-button').

(1) jQuery assumed due to the use of $ in the question.

like image 163
bfavaretto Avatar answered Oct 19 '22 01:10

bfavaretto