0

can you tell me why my code doesn't work. I want to call a function when page is scrolled to certain element. (I would like to find solution in vanilla js without using jQuery)

const numberContainer = document.querySelector('.numbers');

window.addEventListener('scroll', () => {
    const scrolled = window.scrollY;
    const elementPosition = numberContainer.scrollY;
    
    if(scrolled == elementPosition){
        counter();
    }
})
  • Check the IntersectionObserver API https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API – arieljuod Feb 15 '21 at 19:57
  • You will find this answer helpful: https://stackoverflow.com/questions/123999/how-can-i-tell-if-a-dom-element-is-visible-in-the-current-viewport/55181673#55181673 – Randy Casburn Feb 15 '21 at 20:02

2 Answers2

2

Try to use offsetTop for numberContainer

const elementPosition = numberContainer.offsetTop;
ozgebykask
  • 89
  • 3
0

There is no property called scrollY on an HTMLElement (numberContainer in your case). offsetTop is the property you're looking for.

More on it here - https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop

Lakshya Thakur
  • 6,191
  • 1
  • 7
  • 30