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
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.
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.
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.
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).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With