I am trying to manipulate a target object using the intersection observer API once 0.5 of it are within viewport which actually seems to work. However, the callback function also fires straight upon page load and it seems it also fires again once scrolling back up, why's that?
let options = {
root: null, // set the root
rootMargin: '0px',
threshold: 0.5 // 1.0 means 100% of target has to be visible to trigger callback
};
// Declare the target element to manipulate
const target = document.querySelector('.target');
let callback = (entries, observer) => {
entries.forEach(entry => {
target.classList.toggle( 'target-hit' , entries[0].isIntersecting );
console.log('fired')
});
};
// Create intersection observer
let observer = new IntersectionObserver(callback, options);
// Initiate observer to watch for target
observer.observe( target );
.non-target {
height: 1000px
}
.target {
background-color: red;
width: 40px;
height: 40px;
margin-bottom: 30px;
}
.target-hit {
background-color: green
}
<div class="non-target">Non-Target - Please scroll down to target :)</div>
<div class="target">Target</div>