1

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.

jharris94
  • 11
  • 2
  • Does this help? https://stackoverflow.com/questions/26130573/how-to-get-catch-event-off-screen-element – Autex Feb 21 '23 at 07:46

2 Answers2

0

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
  }
})
hi12167pies
  • 175
  • 1
  • 1
  • 9
0

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.

  • This looks good, how would you go about adding a delay to this to prevent bulk actions if a user quickly scrolls? Maybe 5 seconds before the event gets fired again? – jharris94 Feb 21 '23 at 08:29
  • Your question seems to say that you need to operate multiple divs. Isn't it batch operation? –  Feb 21 '23 at 08:43
  • It is, but I want to add a delay to stop the JS action happening more than once every 5 seconds incase a user reaches multiple divs within quick succession. – jharris94 Feb 21 '23 at 09:20