HTML menu color changer
Change menu background when user scroll to a div
by Thet Hlaing
HTML
<header>
https://jsfiddle.net/ThetHlaing10/8g9sapz7/#run <nav>This is top menu</nav>
</header>
<div>
First page
</div>
<div>
Second page
</div>
<div>
Third page
</div>
CSS
body{
margin:0px;
}
div{
height:100vh;
background-color:blue;
border:1px solid black;
}
div:nth-child(2){
padding-top:50px;
}
div:nth-child(3){
background-color:green;
}
header{
height:50px;
background-color:black;
color:#fff;
text-align:center;
width:100%;
transition:all .3s ease;
/*Only one important thing for LMS menu case*/
position:fixed;
}
header.whitebg{
background-color:white;
color:#000;
height:40px;
}
JavaScript
const secondDivTop = document.querySelector('div:nth-child(3)').offsetTop;
window.addEventListener('scroll', function(e) {
console.log(document.documentElement.scrollTop,secondDivTop);
if(document.documentElement.scrollTop > secondDivTop){
document.querySelector('header').classList.add('whitebg');
}
else{
document.querySelector('header').classList.remove('whitebg');
}
});