Skip to content

Instantly share code, notes, and snippets.

@christowiz
Last active November 30, 2018 20:53
Show Gist options
  • Save christowiz/653b76d9e33868e9f0b37a3314762ff2 to your computer and use it in GitHub Desktop.
Save christowiz/653b76d9e33868e9f0b37a3314762ff2 to your computer and use it in GitHub Desktop.
'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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment