Last active
October 13, 2017 05:42
-
-
Save theely/d5e8679b3e89a72b0b7bc96cc3213002 to your computer and use it in GitHub Desktop.
sticky-header-container
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { Component, OnInit, Input,OnChanges, ElementRef,HostListener } from '@angular/core'; | |
| import {SectionComponent} from '../section/section.component'; | |
| @Component({ | |
| selector: 'container', | |
| templateUrl: './container.component.html', | |
| styleUrls: ['./container.component.css'] | |
| }) | |
| export class ContainerComponent implements OnInit { | |
| private currentSectionName: string = null; | |
| private sectionsIndex: any = []; | |
| @Input() sections: any; | |
| constructor( private el: ElementRef) { } | |
| ngOnInit() { | |
| } | |
| sectionPosition($event) { | |
| //filter out the old position if it has been set | |
| this.sectionsIndex = this.sectionsIndex.filter(item => item.name != $event.name); | |
| //set the new position | |
| this.sectionsIndex.push($event); | |
| //sort the section based on their apperance order | |
| this.sectionsIndex.sort((a: any, b: any) => { | |
| return b.position - a.position; | |
| }); | |
| //if the page has already been scrolled find the current name | |
| if (document.body.scrollTop > 0) { | |
| this.currentSectionName = this.getCurrentSectionName(); | |
| } | |
| } | |
| @HostListener("window:scroll", []) | |
| onWindowScroll() { | |
| this.currentSectionName = this.getCurrentSectionName(); | |
| } | |
| private getCurrentSectionName(): string { | |
| let offset: number = this.el.nativeElement.parentElement.offsetTop - this.el.nativeElement.offsetTop; | |
| for (let section of this.sectionsIndex) { | |
| //Note: 13px is the margin-top value of the h2 element in the header | |
| if ((section.position + offset - window.scrollY - 13) < 0) { | |
| return section.name; | |
| } | |
| } | |
| return null; | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fixed issue with document.body.scrollTop