Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use element.offsetBottom?

So I was working on making a sticky nav once you scroll past the hero. I've had no issues using element.offsetTop before. But I'm trying to find a way to do it for the bottom of the element. element.offsetBottom doesn't seem to be a thing. So is there a way to track the bottom on an element in JS?

like image 215
Ryan Mcguinn Avatar asked May 10 '18 21:05

Ryan Mcguinn


People also ask

What is Offsetbottom?

Definition of jQuery offset bottom. The jQuery offset bottom is used to gets the offset of the bottom coordinate for selected elements relative to the documents. The jQuery offset() function is a built-in function in jQuery, by which we can return the offset of the bottom coordinate.

How do you use offsetTop?

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

What is element offsetTop?

Element offsetTop Property The offsetTop property returns the top position (in pixels) relative to the top of the offsetParent element. The returned value includes: the top position, and margin of the element.

How do you find the offset of an element?

jQuery . offset() will get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document. offset() is confused by zoom, at least in Android Chrome, so it is useless.


2 Answers

element.offsetTop is a distance from the element to the nearest positioned element.offsetParent.

So if you want to calculate the distance from element.offsetParent to element bottom edge, if I understand you correctly, you can just

element.offsetBottom = element.offsetTop + element.offsetHeight
like image 69
Karen Grigoryan Avatar answered Nov 15 '22 15:11

Karen Grigoryan


Thanks for the previous answer which pointed me in the right direction to figure this out for my application. Since bottom is measured UP from the bottom of the parent to the bottom of the element, use the offset height of the parent, minus the offset top of the element, minus its height also:

var bottomY = element.offsetParent.offsetHeight - element.offsetTop - element.offsetHeight;

So if the parent was 100px tall, and the element was 10px tall with a bottom:20px position, the offset top would be 70 - subtract that and the element's own 10px height from the the parent's 100 to get back to the 20, or to determine its new bottom position if it's been moved and has a new offset top.

This is currently working to move thumbnails set to bottom:0 at the end of a 100vh container down out of the way and back up again, after also converting to vw units in my case since the thumbnails are scaled that way.

like image 23
Jim Dougherty Avatar answered Nov 15 '22 15:11

Jim Dougherty