Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lock a div when scrolling Angular2

I'm trying keep a div at the top of the screen when I'm scrolling.

I found several guides and SO questions about it, but it's not working for me.

I worked with these :

  • angular2 scroll then fixed header in bootstrap full page modal issue
  • http://brianflove.com/2016/10/10/angular-2-window-scroll-event-using-hostlistener/
  • angular 2 change position to fixed on scroll
  • Angular 4 @HostListener Window scroll event strangely does not work in Firefox

And here's what I've done so far :

component :

import {DOCUMENT} from '@angular/platform-browser';
@Component({
    selector: 'example',
    templateUrl: './example.component.html',
    styleUrls: ['./example.component.css'],
})
export class ExampleComponent implements OnInit {
    public fixed: boolean = false;
    constructor( @Inject(DOCUMENT) private doc: Document) {}
    ngOnInit(): void {
        this.onWindowScroll();
    }
    @HostListener('window:scroll', [])
    onWindowScroll() {
        let number = window.pageYOffset || document.documentElement.scrollTop || window.scrollY || 0;
        if (number > 100) {
            this.fixed = true;
        } else if (this.fixed && number < 10) {
            this.fixed = false;
        }
    }
}

html :

<body>
    <div [class.fixed]="fixed"> some content </div>
    <div> page content </div>
</body>

css :

.fixed{
    position: fixed;
    overflow: auto;
    z-index: 999;
}

I'm using Angular, which is up to date, with a node server and testing on Firefox.

And this doesn't work, with no error in console. Thanks for your help.

like image 773
derOtterDieb Avatar asked Jan 03 '23 12:01

derOtterDieb


1 Answers

Use position as sticky

Plunker Demo: https://plnkr.co/edit/ouqElKKLehPYLexJdIxq?p=preview

.fixed{
        position: sticky;
        top:0;
        z-index: 999;
    }
like image 165
Rohan Fating Avatar answered Jan 19 '23 04:01

Rohan Fating