Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- "use strict";
- let listeners = [];
- let scrollTop = 0;
- let innerWidth = 0;
- let innerHeight = 0;
- let waitForRAF = false;
- const supportsPassive = (function () {
- let supportsPassiveOption = false;
- try {
- const opts = Object.defineProperty({}, 'passive', {
- get: () => {
- supportsPassiveOption = true;
- }
- });
- window.addEventListener('test', null, opts);
- }
- catch (error) {}
- return supportsPassiveOption;
- })();
- export function addListener(func) {
- if (listeners.length === 0) {
- const opts = supportsPassive ? { passive: true } : false;
- window.addEventListener('scroll', handleUpdate, opts);
- window.addEventListener('resize', handleUpdate, false);
- listeners.push(func);
- } else if (!listeners.find(listener => listener === func)) {
- listeners.push(func);
- }
- }
- export function removeListener(func) {
- listeners = listeners.filter(listener => listener !== func);
- if (listeners.length === 0) {
- const opts = supportsPassive ? { passive: true } : false;
- window.removeEventListener('scroll', handleUpdate, opts);
- window.removeEventListener('resize', handleUpdate, false);
- }
- }
- export function triggerListener(func) {
- update();
- func(scrollTop, innerWidth, innerHeight);
- }
- export function triggerAll() {
- update();
- dispatch();
- }
- function handleUpdate(event) {
- update();
- if (!waitForRAF) {
- window.requestAnimationFrame(() => {
- dispatch();
- waitForRAF = false;
- });
- waitForRAF = true;
- }
- }
- function update() {
- const doc = document.documentElement;
- scrollTop = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
- innerWidth = window.innerWidth;
- innerHeight = window.innerHeight;
- }
- function dispatch() {
- listeners.forEach(listener => {
- listener(scrollTop, innerWidth, innerHeight);
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement