Skip to content

Instantly share code, notes, and snippets.

@odahcam
Created October 5, 2018 22:31
Show Gist options
  • Save odahcam/6852ebd888a8c900bba03458a28d6fb9 to your computer and use it in GitHub Desktop.
Save odahcam/6852ebd888a8c900bba03458a28d6fb9 to your computer and use it in GitHub Desktop.
Parallax effect built on top of Angular 6 CDK Scrollable.
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