I have a div that I want to change color when it scrolls into the viewport, and I'm trying to achieve this with the new intersectionObserver
method. I've set my parameters in the config callback, but I can't seem to get the observer itself to add the class to change the background color?
Any help would be amazing.
codepen: https://codepen.io/emilychews/pen/mXVBVK
const config = {
root: null, // sets the framing element to the viewport
rootMargin: '0px',
threshold: 0.5
};
const box = document.getElementById('box');
let observer = new IntersectionObserver(function(entries) {
observer.observe(box);
entries.forEach(function(item){
item.classList.add(active);
});
}, config);
body {
margin: 0; padding: 0;
display:flex;
justify-content: center;
align-items: center;
height: 300vh;
}
#box {
width: 100px;
height: 100px;
background: blue;}
.active {background: red;}
<div id=box></div>