'use strict'; // * Scroll optimization using window.requestAnimationFrame // * // * https://developer.mozilla.org/en-US/docs/Web/Events/scroll // * // * @module scroller // * @param {Object} element DOM element to attach listener to // * @param {Func} cb Callback method to return event object // * @returns {Func} Method to remove event listener from element // // Example: // // componentWillUnmount(){ // this.scroller.remove(); // } // // onEnter = () => { // this.entered = true; // this.content = document.querySelector( '.modal-content' ); // this.scroller = scroller({ // element: document.querySelector( '.aria-modal' ), // cb: this.handleScroll // }); // } // // handleScroll = ( e ) => { // const topPosition = this.content.getBoundingClientRect().top; // // if ( topPosition > -20 && this.state.hideLabel ) this.hideLabel( false ); // if ( topPosition <= -20 && !this.state.hideLabel ) this.hideLabel( true ); // } function scroller(config) { if (!config.callback) throw Error('Scroller missing callback function'); const element = config.element || window; const callback = config.callback; let ticking = false; element.addEventListener('scroll', function(e) { if (!ticking) { window.requestAnimationFrame(function() { callback(e); ticking = false; }); ticking = true; } }); const remove = function() { element.removeEventListener('scroll', callback); }; return { remove, }; } export default scroller;