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?


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

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

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() );