112

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?

Smi
  • 13,850
  • 9
  • 56
  • 64
Denise
  • 1,453
  • 4
  • 14
  • 14

5 Answers5

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

//set
$("#secondElementId").offset({ top: offset.top, left: offset.left});
pstanton
  • 35,033
  • 24
  • 126
  • 168
Steve
  • 50,173
  • 4
  • 32
  • 41
34

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);
KSev
  • 1,859
  • 1
  • 24
  • 23
  • 14
    This answer was voted down twice, with no explanation. Please do tell why, if you down vote my answer. Thanks! – KSev Feb 28 '13 at 22:06
  • 2
    Maybe that's because you use jQuery UI while the OP asks only jQuery. – pram Mar 14 '14 at 21:07
  • 8
    often people go tooooo far with the down voting. Lets not assume that a wider answer is useless to others even if it may be an expansion of the OP. Don't get me started on the 'closed as this is not a proper question' ;) – landed Mar 23 '14 at 20:26
  • @KSev - I'm from the future. jQuery still does not have a setter on `.position`... See: https://api.jquery.com/position/ – Koshinae Mar 29 '16 at 11:34
  • @Koshinae It's part of jQuery "UI". See the link above or try http://jqueryui.com/position/. Also, if you're using jQuery, you may want to consider using angularJS 2.0. However, I expect you're maintaining legacy code. – KSev Mar 29 '16 at 15:59
16

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() );
Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
Amjad Masad
  • 4,035
  • 1
  • 21
  • 20
0

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

var div1Pos = $("#div1").offset();
var div1X = div1Pos.left;
$('#div2').css({left: div1X});
hillspro
  • 745
  • 1
  • 5
  • 13
  • offset().left and css.left are not same thing, they may or may not have the same values depending on the page structure. – Kalle Mar 30 '13 at 23:29
  • I +1'd. It seems to work just fine for me and It is essentially the same as the unchosen answer below that has 85+ votes. – Niko Nov 15 '13 at 18:14
  • Worked for me. Thanks for the contribution! – Erlend K.H. Dec 19 '15 at 07:33
0
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/