Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .offset setting y value

Tags:

jquery

css

offset

I am a newbie to jQuery. Could someone answer this please?

I know I will set layer1 to the position of layer2 with the following line of code.

$("#layer1").offset($("#layer2").offset());

How can I just set the y-value? I'm not sure about that.

Thanks

like image 855
Denise Avatar asked Jan 06 '11 14:01

Denise


People also ask

How do I set relative position in jQuery?

jQuery position() MethodThe position() method returns the position (relative to its parent element) of the first matched element. This method returns an object with 2 properties; the top and left positions in pixels.

How does jQuery calculate offset value?

jQuery offset() MethodThe offset() method set or returns the offset coordinates for the selected elements, relative to the document. When used to return the offset: This method returns the offset coordinates of the FIRST matched element. It returns an object with 2 properties; the top and left positions in pixels.

What is offset () Top?

Definition and Usage The offsetTop property returns the top position (in pixels) relative to the parent. The returned value includes: the top position, and margin of the element.

What is offsetHeight in jQuery?

offsetHeight read-only property returns the height of an element, including vertical padding and borders, as an integer. Typically, offsetHeight is a measurement in pixels of the element's CSS height, including any borders, padding, and horizontal scrollbars (if rendered).


1 Answers

The jQuery documentation for .offest() reads:

.offset() returns an object containing the properties top and left.

Knowing this, you can accomplish the following:

var offset = $("#layer2").offset();
$("#layer1").css({
    'top' : offset.top,
    'left': offset.left
});  

Or, you can set them individually, per your requirement.

$("#layer1").css('top', offset.top);  // or...
$("#layer1").css('left', offset.left);

Finally, since you only need a single value (top), offset is overkill; it's more expensive than you need. Use the following, optimized snippet instead.

var top = $('#layer2').css('top');
$('#layer1').css('top', top);
like image 159
Stephen Avatar answered Sep 23 '22 13:09

Stephen