sairaj sairaj - 2 months ago 10
HTML Question

Change header background and font-color after scrolling through gray section

I want to add a class to header after (gray)section scroll is over. And remove the same class when (gray)section reappers on scroll-up.
https://jsfiddle.net/tgLybw2e/1/

$(window).scroll(function(event){
didScroll = true;
});

Answer Source

You can use a window.onscroll function along with window.scrollY to detect when the screen has scrolled to the bottom of the gray element, then add a class.

This could be made more dynamic by using JS to get the height of the gray element so it doesn't need to be hardcoded to the same value as set in CSS.

window.onscroll = function() {
  var header = document.getElementById('header');
  if (window.scrollY > 630) {
    header.classList.add('updated-class');
  } else {
    header.classList.remove('updated-class');
  }
}
header{
  height: 70px;
  border-bottom: 1px solid #000;
  position: fixed;
  color: #fff;
  left:0;
  right:0;
  text-align:center;
}
header.changeColor{
  color: 000;
}
section{
  height: 700px;
  background: #cdcdcd;
}
section + section{
  background: #fff;
}
.red{
  background:red;
}

.updated-class {
  background-color: red;  
  transition: background 1s linear;
}
<header id="header">
abcfdff
</header>
<section>

</section>
<section>

</section>
<section class="red">

</section>