Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to position a div dynamically below another?

Tags:

jquery

dom

I'm trying to use jQuery to detect the position of a div (#olddiv), so I can use that position to place another div (#newdiv) exactly below it. The right borders of the 2 divs are aligned (right border).

I'm trying to get the #olddiv bottom and right locations to use them as the #newdiv top and right borders. I've used this code, but it's not working. Any idea what I'm doing wrong?

var right = $('#olddiv').position().right;
var top = $('#olddiv').position().bottom;
$('#newdiv').css('top', right);
$('#newdiv').css('right', top);     

Also, I'm not sure if position is what I need. I think this can be done with position or offset, but I'm not sure:

$('#ID').position().left
$('#ID').offset().left

Thanks

like image 965
Fred Avatar asked Dec 05 '09 01:12

Fred


People also ask

How to change position of div dynamically in jQuery?

Here's the code: // function to place the div var newdiv = function () { var o = $('#olddiv'). offset(); var h = $('#olddiv'). height(); var w = $('#olddiv').

How do I place one div to the right of another?

Use CSS property to set the height and width of div and use display property to place div in side-by-side format. float:left; This property is used for those elements(div) that will float on left side. float:right; This property is used for those elements(div) that will float on right side.

What is a dynamic Div?

Dynamic disks are a separate form of volume management that allows volumes to have noncontiguous extents on one or more physical disks. Dynamic disks and volumes rely on the Logical Disk Manager (LDM) and Virtual Disk Service (VDS) and their associated features.


2 Answers

I've used offset() to position elements dynamically. Try this:

var offset = $('#olddiv').offset();
var height = $('#olddiv').height();
var width = $('#olddiv').width();
var top = offset.top + height + "px";
var right = offset.left + width + "px";

$('#ID').css( {
    'position': 'absolute',
    'right': right,
    'top': top
});

also don't forget to bind this to the window.onresize event if you need it to scale when the user resizes the window.

UPDATE: another thought - does this have to be positioned absolutely? Why not just insert the div after the other in the DOM?

$('#olddiv').after($('#ID').html());

then just make sure they are the same width.

like image 75
Jared Avatar answered Oct 08 '22 19:10

Jared


There is a pretty cool plugin getting developed by the jQuery UI team that helps with position.

Lets you do something like this:

$(".menu").position({ my: "left top", at: "left bottom", of: ".menubutton" });
like image 23
PetersenDidIt Avatar answered Oct 08 '22 18:10

PetersenDidIt