Created
October 5, 2018 22:31
-
-
Save odahcam/6852ebd888a8c900bba03458a28d6fb9 to your computer and use it in GitHub Desktop.
Parallax effect built on top of Angular 6 CDK Scrollable.
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 { Directive, Input, ElementRef } from '@angular/core'; | |
import { ScrollDispatcher, CdkScrollable } from '@angular/cdk/overlay'; | |
@Directive({ | |
selector: '[appParallax]' | |
}) | |
export class ParallaxDirective { | |
el: HTMLElement; | |
initialTop: number = 0; | |
@Input('ratio') | |
parallaxRatio: number = .2; | |
constructor( | |
readonly elRef: ElementRef, | |
private readonly scroll: ScrollDispatcher, | |
) { | |
this.el = elRef.nativeElement; | |
this.initialTop = this.el.getBoundingClientRect().top; | |
this.el.style.position = 'relative'; | |
this.scroll.scrolled().subscribe(x => this.onScroll(x || undefined)); | |
// this.scroll.ancestorScrolled(elRef).subscribe(() => console.log('ancestor scroll')); | |
} | |
onScroll(scrollable?: CdkScrollable) { | |
if (!scrollable) { | |
return; | |
} | |
const scrolledElem: HTMLElement = scrollable.getElementRef().nativeElement; | |
const scrollY = scrolledElem.scrollTop; | |
const parallax = this.initialTop + scrollY * this.parallaxRatio; | |
this.el.style.top = `${parallax}px`; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment