skip to Main Content

We are looking to fire a JS event each time the top of the users browser passes a repeating div. For example.

<div class="refresh"></div>

If the above div was repeated multiple times on a page, we want to fire a specific event each time it is scrolled past (However, once it goes out of view on the top of the page rather than when it comes into view).

I have tried it but I can only get it to fire once rather than look for multiple divs.

2

Answers


  1. this seems to work, there is probably a better way to do it.

    const div = document.getElementById("refresh")
    
    let isInView = false
    
    document.addEventListener("scroll", e => {
      const bounding = div.getBoundingClientRect()
    
      if (bounding.top < bounding.height && bounding.top > 0) {
    
        // if you want it to only fire once when it comes into view
        if (isInView) return
        isInView = true
    
        console.log("In view!")
        // do other stuff...
      } else {
        isInView = false
      }
    })
    
    Login or Signup to reply.
  2. Use IntersectionObserver judgment:

    const refreshDoms = document.querySelectorAll('.refresh');
    
    const observer = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        // refresh element out of view
        if (!entry.isIntersecting) {
          // fire JS event code
        }
      });
    });
    
    refreshDoms.forEach(dom=> observer.observe(dom));
    

    https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver
    And if you use IntersectionObserver, you need to consider browser compatibility.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search