-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsetClassInView.ts
48 lines (38 loc) · 1.4 KB
/
setClassInView.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
import {Directive, ElementRef, Renderer, Input, HostListener} from '@angular/core';
@Directive({
selector: '[setClassInView]'
})
export class SetClassInView {
@Input('setClassInView') className:string;
private el:ElementRef;
private renderer:Renderer;
constructor(el: ElementRef, renderer: Renderer) {
this.el = el;
this.renderer = renderer;
}
@HostListener('window:scroll', ['$event'])
private setClassWhenInView():void {
this.renderer.setElementClass(this.el.nativeElement, this.className, SetClassInView.isInView(this.el));
}
private static isInView(el): boolean {
let viewport = {
top: window.scrollY,
left: scrollX
};
var rect = el.nativeElement.getBoundingClientRect();
var bounds = {
top: rect.top + document.body.scrollTop,
left: rect.left + document.body.scrollLeft
};
bounds['right'] = bounds.left + el.nativeElement.outerWidth;
bounds['bottom'] = bounds.top + el.nativeElement.outerHeight;
viewport['right'] = viewport.left + window.innerWidth;
viewport['bottom'] = viewport.top + window.innerHeight;
return(
!(viewport['right'] < bounds.left
|| viewport.left > viewport['right']
|| viewport['bottom'] < bounds.top
|| viewport.top > viewport['bottom'])
);
}
}