i have this code that updates a number from 2019 to 2022 but i want it to only run when the component is in view, meaning if they haven't scrolled to that part of the page the effect shouldn't run
useEffect(() => {
setTimeout(() => {
setTitle(2020)
}, 2000)
setTimeout(() => {
setTitle(2021)
}, 4000)
setTimeout(() => {
setTitle(2022)
}, 6000)
}, []);
at the moment it updates the value even when you haven't scrolled down to that part of the page, is there a way to make useEffect only activate when scrolled to that section of the page or do you need to do it completely differently?
window.addEventListener('scroll', function() {
var element = document.querySelector('#main-container');
var position = element.getBoundingClientRect();
// checking whether fully visible
if(position.top >= 0 && position.bottom <= window.innerHeight) {
console.log('Element is fully visible in screen');
}
// checking for partial visibility
if(position.top < window.innerHeight && position.bottom >= 0) {
console.log('Element is partially visible in screen');
}
});
Snippet from https://usefulangle.com/post/113/javascript-detecting-element-visible-during-scroll. Paste your code to the part where an element is fully in view. Remember to query select the element you want to have in view first.