I have a block with position: sticky and a block under it. Is there any way to track the moment when the sticky block sticks to the top and add a class to the bottom block?
I think I should use $(window).scroll() but don't know how.
I have a block with position: sticky and a block under it. Is there any way to track the moment when the sticky block sticks to the top and add a class to the bottom block?
I think I should use $(window).scroll() but don't know how.
There is no "official" way of telling an element is being stuck with sticky positioning as I know of right now. But you could use a IntersectionObserver.
It works by observing changes in an elements position related for example to a viewport, in the case of this code sample it checks for at least a 1px difference (threshold: 1).
const el = document.querySelector(".stickyElement")
const observer = new IntersectionObserver(
([e]) => document.querySelector(".elementThatShouldUpdate").classList.toggle("desired-class", e.intersectionRatio < 1),
{ threshold: [1] }
);
observer.observe(el);
You should also update your CSS for the sticky element to account for the 1px difference:
top: -1px;
And also account for this extra offset, so you should add either a border or a padding to this element:
padding-top: 1px;
Let me know if this helps.