I am utilizing an intersection observer that alters the header's font-color
and background-color
based on the content intersecting with it. This change is determined by the presence of data-color
and data-background
attributes declared on the div/section elements.
In its default state, when no attributes are specified on a div/section, the header should remain unchanged. However, currently, it retains its last modification and does not revert to the default settings. Therefore, my inquiry is regarding how to implement a mechanism to return/remove the header back to its default state within the existing script? In the provided fiddle example, you will notice that the second div without any attributes specified fails to reset the header to its default appearance of black text on a green background.
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: sans-serif;
}
.g-100vh {
height: 100vh
}
header {
min-height: 50px;
position: fixed;
background-color: green;
color: black;
width: 100%;
}
Intersection Observer
const header = document.querySelector('header');
const sections = document.querySelectorAll('div');
const config = {
rootMargin: '0px',
threshold: [0.05, 0.95]
};
const observer = new IntersectionObserver(function (entries, self) {
entries.forEach(entry => {
if (entry.isIntersecting) {
if (entry.intersectionRatio > 0.95) {
header.style.color = entry.target.dataset.color;
header.style.background = entry.target.dataset.background;
} else {
if (entry.target.getBoundingClientRect().top < 0 ) {
header.style.color = entry.target.dataset.color;
header.style.background = entry.target.dataset.background;
}
}
}
});
}, config);
sections.forEach(section => {
observer.observe(section);
});