export default class ElementIsInView {
constructor(params) {
if (!params.element) return;
const {
element,
onViewTopHide,
onViewBottomHide,
onViewCenterShow,
onViewTopIng,
onViewBottomIng,
} = params;
this.element = element || '';
this.onViewTopHide = onViewTopHide || null;
this.onViewBottomHide = onViewBottomHide || null;
this.onViewCenterShow = onViewCenterShow || null;
this.onViewTopIng = onViewTopIng || null;
this.onViewBottomIng = onViewBottomIng || null;
this.windowHeight = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
this.listenerFunction = this.scrollEventListen.bind(this);
window.addEventListener('scroll', this.listenerFunction, true);
}
destroy() {
window.removeEventListener('scroll', this.listenerFunction, true);
}
getBoundingRect(element) {
const rect = element.getBoundingClientRect();
const top = document.documentElement.clientTop || 0;
const left = document.documentElement.clientLeft || 0;
return {
top: rect.top - top,
bottom: rect.bottom - top,
left: rect.left - left,
right: rect.right - left,
width: rect.width,
height: rect.height
};
}
scrollEventListen() {
const elementBounding = this.getBoundingRect(this.element);
const { top, bottom, height } = elementBounding;
if (bottom <= 0) {
if (this.onViewTopHide && typeof this.onViewTopHide === 'function') {
this.onViewTopHide();
}
}
if (top >= this.windowHeight) {
if (this.onViewBottomHide && typeof this.onViewBottomHide === 'function') {
this.onViewBottomHide();
}
}
if (top > 0 && top < this.windowHeight && bottom > 0 && bottom < this.windowHeight) {
if (this.onViewCenterShow && typeof this.onViewCenterShow === 'function') {
this.onViewCenterShow();
}
}
if (top <= 0 && bottom <= height && bottom > 0) {
if (this.onViewTopIng && typeof this.onViewTopIng === 'function') {
this.onViewTopIng();
}
}
if (top < this.windowHeight && bottom >= this.windowHeight) {
if (this.onViewBottomIng && typeof this.onViewBottomIng === 'function') {
this.onViewBottomIng();
}
}
}
elementInViewStatus() {
const elementBounding = this.getBoundingRect(this.element);
const { top, bottom, height } = elementBounding;
if (bottom <= 0) return 'top-hide';
if (top >= this.windowHeight) return 'bottom-hide';
if (top > 0 && top < this.windowHeight && bottom > 0 && bottom < this.windowHeight) return 'center-show';
if (top <= 0 && bottom <= height && bottom > 0) return 'top-ing';
if (top < this.windowHeight && bottom >= this.windowHeight) return 'bottom-ing';
}
}
import ElementIsInView from 'element-is-in-view';
const eleIsInView = new ElementIsInView({
element: document.querySelector('#banner'),
onViewTopHide: () => {},
onViewBottomHide: () => {},
onViewTopIng: () => {},
onViewBottomIng: () => {},
onViewCenterShow: () => {}
});
const curStatus = eleIsInView.elementInViewStatus();
eleIsInView.destroy();