Reputation: 418
I am attempting to implement a solution where by as you scroll through various sections of my site, marked by the
<section>
</section>
HTML Tags, the:
<meta name="theme-color" content="#535353">
Changes, say for example you had 3 sections, the first had a Black background, second white, and third red- as you scrolled through each section, the theme-colour changed appropriately. So far I have:
document.querySelector('meta[name="theme-color"]').setAttribute('content', '#535353');
However I am unsure where to go from here. I hope you guys will be able to help me out, thanks.
Upvotes: 1
Views: 789
Reputation: 790
Below code does the trick:
css:
section {
height: 100vh;
display: block;
}
html:
<section data-theme-color="red">
<p>sesction conent</p>
</section>
<section data-theme-color="green">
<p>sesction conent</p>
</section>
<section data-theme-color="blue">
<p>sesction conent</p>
</section>
and js:
var theme = document.querySelector('meta[name="theme-color"]'),
getThemeColor = theme.getAttribute('content'),
sectionElem = document.getElementsByTagName('section'),
sectionHeight = sectionElem[0].clientHeight,
sectionLength = sectionElem.length;
// set color on load
window.onload = () => {
document.body.style.backgroundColor = theme.getAttribute('content');
}
// set color on 'scroll' event
window.addEventListener('scroll', (e) => {
var offset = window.pageYOffset,
sectionIndex = parseInt(offset, "10") % sectionLength,
sectionColor = document.getElementsByTagName('section')[sectionIndex].getAttribute('data-theme-color'),
setSectionColor = theme.setAttribute('content', sectionColor);
document.querySelectorAll('section')[sectionIndex].style.backgroundColor = theme.getAttribute('content');
});
Upvotes: 2