dataviews
dataviews

Reputation: 3090

Detect element hiding/showing

What is the best way to keep watch on a specific element, and trigger a function whenever the visibility of the element changes; visible vs. hidden?

I've tried with ways like new window.MutationObserver, but haven't had any luck.

Upvotes: 0

Views: 182

Answers (1)

Spectric
Spectric

Reputation: 31987

Use an IntersectionObserver and check the element's intersectionRatio:

index=0,setInterval(() => elem.style.display = ++index % 2 == 0 ? "block" : "none", 1000)
// ^^^flicker effect^^^

const observer = new IntersectionObserver((elems, obs) => {
  if(elems[0].intersectionRatio == 0) {
    console.log('elem hidden')
  } else {
    console.log('elem shown')
  }
})
observer.observe(elem)
<div id="elem">Flickering text</div>

Upvotes: 2

Related Questions