I am currently using this bit of code to detect if #myDiv, which is in position: sticky
, is currently pinned or not and add a class when it is:
const myDiv = document.querySelector("#myDiv")
const observer = new IntersectionObserver(
([e]) => e.target.classList.toggle("sticky", e.intersectionRatio < 1),
{ threshold: [1] }
);
observer.observe(myDiv);
It works like a charm but I have a big issue. When #myDiv, which is sticked to the bottom of the viewport, is not sticky anymore its height changes therefore triggering the above function and entering an infinite loop.
To fix this problem I want to limit the execution of my function to a condition: If the user has scrolled 200 pixels upward or downward since last execution of the function, the function can be executed again.
Thanks a lot for your help on this.
edit: I've added a simplified version of my problem. You can see my issue by slowly scrolling to the point where #mydiv isn't pinned anymore.
const myDiv = document.querySelector("#mydiv")
const observer = new IntersectionObserver(
([e]) => e.target.classList.toggle("sticky", e.intersectionRatio < 1),
{ threshold: [1] }
);
observer.observe(myDiv);
body{color:#333; font-family:arial; font-weight:bold; font-size:40px; }
.main-container{ max-width:600px; margin:0 auto; border:solid 10px green; padding:10px; margin-top:40px;}
.main-container *{background border:dashed 1px #333;}
.main-container * + *{margin-top:20px;}
.main-header{
height:50px; background:#aaa;
}
.main-content{
min-height:1000px;
}
#mydiv{position:-webkit-sticky; position:sticky; bottom:-1px; border-color:red;background: red;}
.content {font-size: 16px;padding:0;text-align: center}
#mydiv.sticky .content {display: none;}
<main class="main-container">
<header class="main-header">HEADER</header>
<div class="main-content">MAIN CONTENT</div>
<div id="mydiv">
<p class="content">Content 1</p>
<p class="content">Content 2</p>
<p>MyDiv</p>
</div>
<footer>FOOTER</footer>
</main>
<br><br><br><br>