Skip to content

Instantly share code, notes, and snippets.

@jrobinsonc
Created July 4, 2021 21:39
Show Gist options
  • Save jrobinsonc/22f3d7c5fcaf17b2412b5fd4cf7e23b3 to your computer and use it in GitHub Desktop.
Save jrobinsonc/22f3d7c5fcaf17b2412b5fd4cf7e23b3 to your computer and use it in GitHub Desktop.
;
(function ($, undefined) {
$.fn.handleScroll = (upHandler, downHandler, userOptions) => {
const options = $.extend({}, {
debug: false
}, userOptions);
/**
* Window object.
*/
const $Window = this;
/**
* States if the document is already loaded.
*/
let isLoaded = false;
/**
* Last scroll position.
*/
let lastScrollTop = 0;
jQuery(document).ready(() => {
isLoaded = true;
if (options.debug) {
console.log("[handleScroll] Window loaded");
}
});
$Window.on("scroll", () => {
if (!isLoaded) {
return;
}
const scrollTop = $Window.scrollTop();
if (scrollTop > lastScrollTop) {
if (options.debug) {
console.log("[handleScroll] Window scrolling down");
}
downHandler();
} else {
if (options.debug) {
console.log("[handleScroll] Window scrolling up");
}
upHandler();
}
lastScrollTop = scrollTop;
});
return $Window;
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment