I am trying to find out when I have passed certain element while scrolling.
const elementTarget = document.getElementById('sidebar');
window.addEventListener('scroll', () => {
if (window.scrollY > elementTarget.offscrollTop) {
console.log('passed an element');
}
})
sample code: https://codepen.io/RomanKomprs/pen/LMrPNJ
EDITED: The code above doesn't work. When I scroll down and the scrollY is bigger than the offset of my sidebar element the condition doesn't trigger. What am I doing wrong?
Replace offscrollTop
with getBoundingClientRect().top
const elementTarget = document.getElementById("sidebar");
window.addEventListener("scroll", () => {
if (window.scrollY > elementTarget.getBoundingClientRect().top) {
console.log("passed an element");
}
});
First, you have to elements with equal id; Second you need to use .offsetTop for get value of offset;
if (window.scrollY > elementTarget1.offsetTop) {
console.log('passed an element');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.