0

I tried to use IntersectionObserver to check, when an element (button) is visible.

But when i tab out, so the tab is inactive, he doesnt see it anymore. When i tab in, he sends the console.log found instantly.

Any ideas, if there is a way, to check if the button is visible

const observer = new IntersectionObserver(([entry]) => { if (entry.isIntersecting) { console.log('found') }, { root: null, threshold: 0.1, // set offset 0.1 means trigger if atleast 10% of element in viewport }) observer.observe(document.querySelector(el)); 

I also tried MutationObserver but that cannot check if the button is in view. Just checking if there is code in background. And when its one time there, its there forever, also when its invisible than.

I just want to check if the button can be clicked right now, nothing more. But with MutationObserver he spams found, cause he found the code in background, also when the button is not in view.

I tried to search for someone with the same problem. Also tried mutationObserver but thats not the same.

1

1 Answer 1

0

Once try like this

Observe the target element and trigger the callback when the element is at least 10% visible in the viewport.

Listens for when the document's visibility changes (i.e., when the user tabs in or out). When the tab becomes active, it manually checks the element's visibility using its bounding rectangle.

const observer = new IntersectionObserver(([entry]) => { if (entry.isIntersecting) { console.log('found'); } }, { root: null, threshold: 0.1 // Trigger when at least 10% of the element is in the viewport }); const targetElement = document.querySelector(el); observer.observe(targetElement); // Handle tab visibility change document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') { // Manually check if the element is visible when the tab becomes active const rect = targetElement.getBoundingClientRect(); const isVisible = ( rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth) ); if (isVisible) { console.log('found'); } } }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.