Search code examples
javascriptscrollbooleanwindow

How to know if my element was already present on the screen js


I have this function to know if my element is on my screen :

function isInViewport(element) {
const rect = element.getBoundingClientRect();
return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
        );
}

But I would to print something when this element is on my screen only one time when I scroll down. My code:

window.addEventListener("scroll", function() {
   if (isInViewport(element)) {
    console.log('test');
  }
  })

The problem is with that, my function is called so many times during the scrolling time. So my idea was to print 'test' if it was not on the screen, and don't print it again if it was already on the screen. But I don't know how to do that..


Solution

  • create a flag above hasAppeared = false, then update the function:

    window.addEventListener("scroll", function() {
        if (isInViewport(element) && !hasAppeared) {
            hasAppeared = true;
            console.log('test');
        }
    })
    

    Or if it's a one time thing, you can remove the eventListener on scroll after you console.log it for the first time.