Reputation: 825
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?
Upvotes: 11
Views: 26447
Reputation: 51
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.
Upvotes: 4
Reputation: 5432
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
Upvotes: 20