Latest update: Still unsolved...
Example:
I started this question with the scroll event approach, but due to the suggestion of using IntersectionObserver which seems much better approach i'm trying to get it to work in that way.
What is the goal:
I would like to change the style (color+background-color) of the header depending on what current div/section is observed by looking for (i'm thinking of?) its class or id that will override the default header style (black on white).
Header styling:
font-color:
Depending on the content (div/section) the default header should be able to change the font-color into only two possible colors:
- black
- white
background-color:
Depending on the content the background-color could have unlimited colors or be transparent, so would be better to address that separate, these are the probably the most used background-colors:
- white (default)
- black
- no color (transparent)
CSS:
header {
position: fixed;
width: 100%;
top: 0;
line-height: 32px;
padding: 0 15px;
z-index: 5;
color: black; /* default */
background-color: white; /* default */
}
.white-menu {
color: white;
background-color: transparent; /* separate as style on content if needed */
}
.black-menu {
color: black;
background-color: transparent; /* separate as style on content if needed */
}
Div/section example with default header no change on content:
<div class="grid-30-span g-100vh">
<img
src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1.414 1'%3E%3C/svg%3E"
data-src="/images/example_default_header.jpg"
class="lazyload"
alt="<?php echo $title; ?>">
</div>
Div/section example change header on content:
<div class="grid-30-span g-100vh white-menu" style"background-color:darkblue;">
<img
src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1.414 1'%3E%3C/svg%3E"
data-src="/images/example_darkblue.jpg"
class="lazyload"
alt="<?php echo $title; ?>">
</div>
<div class="grid-30-span g-100vh black-menu" style"background-color:lightgrey;">
<img
src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1.414 1'%3E%3C/svg%3E"
data-src="/images/example_lightgrey.jpg"
class="lazyload"
alt="<?php echo $title; ?>">
</div>
Intersection Observer approach:
const sections = document.querySelectorAll('div');
const config = {
rootMargin: '-50px 0px 0px 0px'
};
const observer = new IntersectionObserver(function (entries, self) {
entries.forEach(entry => {
if (entry.isIntersecting) {
$('header').css({
"color": $(this).id('color'),
"background-color": $(this).id('background-color')
});
}
});
}, config);
sections.forEach(section => {
observer.observe(section);
});
from Change style header/nav with Intersection Observer (IO)

No comments:
Post a Comment