[jquery] Get and set position with jQuery .offset()

How to get and set the position of an element with the jQuery .offset method?

Let's say I have a div layer1 and another layer2. How can I get the position of layer1 and set the same position to layer2?

This question is related to jquery

The answer is


Here is an option. This is just for the x coordinates.

var div1Pos = $("#div1").offset();
var div1X = div1Pos.left;
$('#div2').css({left: div1X});

var redBox = $(".post");

var greenBox = $(".post1");

var offset = redBox.offset();

$(".post1").css({'left': +offset.left});
$(".post1").html("Left :" +offset.left);

http://jsfiddle.net/va836/159/


I recommend another option. jQuery UI has a new position feature that allows you to position elements relative to each other. For complete documentation and demo see: http://jqueryui.com/demos/position/#option-offset.

Here's one way to position your elements using the position feature:

var options = {
    "my": "top left",
    "at": "top left",
    "of": ".layer1"
};
$(".layer2").position(options);

It's doable but you have to know that using offset() sets the position of the element relative to the document:

$('.layer1').offset( $('.layer2').offset() );

//Get
var p = $("#elementId");
var offset = p.offset();

//set
$("#secondElementId").offset({ top: offset.top, left: offset.left});