my-div element has position absolute. When you scroll the page, as soon as my-div is out of the view port its position changes to fixed and top: 0. Here I need to change the value 0 for top to 100px.
I managed to do so by using onscroll method as follow:
document.onscroll = function(){
const myDiv = document.querySelector('.my-div')
if(myDiv && myDiv.style.position == 'fixed') {
myDiv.style.top = '100px';
}
}
The above code is working. However, the problem with this code is that it fires on each scroll event and is bad for performance. Now I'm trying to use intersectionObserver method instead of onscroll method.
What I need is: As soon as my-div isn't in the viewport and its position is fixed, add top 100px to it.
I tried this:
const myDiv = document.querySelector('.my-div');
if (myDiv) {
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting === false && myDiv.style.position == 'fixed') {
myDiv.style.top = '100px';
observer.unobserve(entry.target);
}
});
});
observer.observe(myDiv);
}
But it's not working.