skip to Main Content

Need help changing my header background color when scrolling. This is what i have thus far.

header.component.ts

export class HeaderComponent {

  ngOnInit(): void {
    const header = document.querySelector('.header');
    document.addEventListener('scroll', (ev) => {
      if (header !== null) {
        if (window.scrollY === 0) {
          header.classList.remove('change-header-background');
          return;
        }
        header.classList.add('change-header-background');
      }
    });
  }

}

header.component.scss

.header {
    border-top: 0.5rem solid #000;
    position: fixed;

    .change-header-background {
        background-color: white;
    }    
}

I have tried multiple suggestions i have found online, but none seemed to work.

2

Answers


  1. If you want to do any animation When scrolling you may use the GSAP Library
    https://greensock.com/scrolltrigger/

    Login or Signup to reply.
  2. Just a suggestion not a solution, but I suggest trying to animate the background change using @keyframes in your css instead of doing it in your ts component.

    you could write something like this

    @keyframes headerColorChange {
      0% {background-color: black;}
      50.0% {background-color: white;}
      100% {background-color: black;}
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search