This repository was archived by the owner on Oct 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathparallax.ts
56 lines (48 loc) · 1.96 KB
/
parallax.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
module Parallax {
export class ParallaxContainer {
private content: HTMLElement;
private perspective: number;
private surface: ParallaxSurface[];
/**
* Creates a Container for a Parallax
*
* @param {HTMLElement} scrollableContent The container that will be parallaxed
* @param {perspective} perspective The ratio of how much back content should be scrolled relative to forward content. For example, if this value is 0.5, and there are 2 surfaces,
* the front-most surface would be scrolled normally, and the surface behind it would be scrolled half as much.
*/
constructor(scrollableContent: HTMLElement,
perspective: number) {
this.perspective = perspective;
this.surface = [];
this.content = scrollableContent;
$(scrollableContent).scroll((event: JQueryEventObject) => {
this.onContainerScroll(event);
});
}
private onContainerScroll(e: JQueryEventObject): void {
var currentScrollPos = $(this.content).scrollTop();
var currentParallax = 1;
for (var i = 0; i < this.surface.length; i++) {
var surface = this.surface[i];
var offset = -(currentScrollPos * currentParallax);
surface.currentY = offset;
currentParallax *= this.perspective;
}
}
addSurface(surface: ParallaxSurface): void {
this.surface.push(surface);
}
}
export class ParallaxSurface {
private content: HTMLElement;
constructor(surfaceContents: HTMLElement) {
this.content = surfaceContents;
}
get currentY(): number {
return -$(this.content).css('margin-top');
}
set currentY(value: number) {
$(this.content).css({ marginTop: value });
}
}
}