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
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);
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});
Source: Stackoverflow.com