-1

Tried to change the background color on scroll to the sticky header but not working. How to do it? when I scroll to the bottom of the body I need to change the header background color. How to do it?

app.component.html

<div class="header sticky">
</div>

app.component.css

 .sticky {
 position: -webkit-sticky;
 position: sticky;
 top: 0px;
 }

Demo: https://stackblitz.com/edit/sticky-header-hyibz9?file=app%2Fheader%2Fheader.component.css

Noxin D Victus
  • 386
  • 1
  • 5
  • 17
Sansara
  • 85
  • 3
  • 15

2 Answers2

1

You can use ngClass for this and HostListener to check if user scrolled at the buttom

html

<div class="header sticky" [ngClass]="isBottom ? 'bottom' : 'top'">
</div>

ts

import { Component, OnInit, HostListener } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
  isBottom: boolean;

  constructor() {}

  ngOnInit() {}

  @HostListener('window:scroll', [])
  onScroll(): void {
    if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
      this.isBottom = true;
    } else {
      this.isBottom = false;
    }
  }
}

css

.sticky {
  position: -webkit-sticky;
  position: sticky;
  top: 0px;
}

.header {
  height: 50px;
}

.top {
  background-color: blue;
}

.bottom {
  background-color: yellow;
}

Noxin D Victus
  • 386
  • 1
  • 5
  • 17
0
import { Component, OnInit, HostListener } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
  isBottom: boolean;

  constructor() {}

  ngOnInit() {}

  @HostListener('window:scroll', [])
  onScroll(): void {
    if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
      this.isBottom = false;
    } else if (window.scrollY) {
      this.isBottom = false;
    } else  {
      this.isBottom = true;
    }
  }
}
Bhatt
  • 1
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 01 '21 at 13:38