jellyfin-web/dashboard-ui/components/scrollthreshold.js

95 lines
2.8 KiB
JavaScript
Raw Normal View History

2016-04-23 13:30:45 -07:00
define(['events'], function (events) {
function thresholdMonitor(elem, horizontal, lowerTolerance, upperTolerance) {
2016-04-24 16:14:55 -07:00
var defaultTolerance = horizontal ? (screen.availWidth / 3) : (screen.availHeight / 3);
2016-04-23 13:30:45 -07:00
lowerTolerance = lowerTolerance || defaultTolerance;
upperTolerance = upperTolerance || defaultTolerance;
var self = this;
2016-04-24 16:14:55 -07:00
var upperTriggered = true;
2016-04-23 13:30:45 -07:00
var lowerTriggered = false;
2016-04-24 16:14:55 -07:00
var isWindow = elem == window || elem.tagName == 'HTML' || elem.tagName == 'BODY';
2016-04-23 13:30:45 -07:00
var scrollSize;
function getScrollSize() {
if (!scrollSize) {
2016-04-24 16:14:55 -07:00
if (isWindow) {
scrollSize = horizontal ? (document.documentElement.scrollWidth - document.documentElement.offsetWidth) : (document.documentElement.scrollHeight - document.documentElement.offsetHeight);
} else {
scrollSize = horizontal ? (elem.scrollWidth - elem.offsetWidth) : (elem.scrollHeight - elem.offsetHeight);
}
2016-04-23 13:30:45 -07:00
}
return scrollSize;
}
function onScroll(e) {
if (lowerTriggered && upperTriggered) {
return;
}
2016-04-24 16:14:55 -07:00
var position;
if (isWindow) {
position = horizontal ? window.pageXOffset : window.pageYOffset;
} else {
position = horizontal ? elem.scrollLeft : elem.scrollTop;
}
2016-04-23 13:30:45 -07:00
2016-04-23 13:49:14 -07:00
//console.log('onscroll: ' + position + '-' + getScrollSize());
2016-04-23 13:30:45 -07:00
// Detect upper threshold
2016-04-24 16:14:55 -07:00
if (position < upperTolerance) {
if (!upperTriggered) {
upperTriggered = true;
events.trigger(self, 'upper-threshold');
}
} else {
upperTriggered = false;
2016-04-23 13:30:45 -07:00
}
2016-04-24 16:14:55 -07:00
2016-04-23 13:30:45 -07:00
// Detect lower threshold
2016-04-24 16:14:55 -07:00
if (position >= (getScrollSize() - lowerTolerance)) {
if (!lowerTriggered) {
lowerTriggered = true;
events.trigger(self, 'lower-threshold');
}
} else {
2016-04-23 13:30:45 -07:00
lowerTriggered = false;
}
}
self.reset = function () {
self.resetSize();
2016-04-24 16:14:55 -07:00
upperTriggered = true;
2016-04-23 13:30:45 -07:00
lowerTriggered = false;
};
self.resetSize = function () {
scrollSize = null;
};
self.enabled = function (enabled) {
self.reset();
if (enabled) {
elem.addEventListener('scroll', onScroll, true);
} else {
elem.removeEventListener('scroll', onScroll, true);
}
};
self.enabled(true);
self.destroy = function () {
self.enabled(false);
};
}
return thresholdMonitor;
});