Skip to content

Instantly share code, notes, and snippets.

@jrobinsonc
Last active February 5, 2019 18:44
Show Gist options
  • Save jrobinsonc/e1dac81128d23884d8ca8dab7455d965 to your computer and use it in GitHub Desktop.
Save jrobinsonc/e1dac81128d23884d8ca8dab7455d965 to your computer and use it in GitHub Desktop.
jquery.handleScroll

jQuery HandleScroll Plugin

Usage

Pretty simple:

jQuery(function($) {
  $( window ).handleScroll(function() {
    // going up
  }, function() {
    // going down
  }, {
    debug: true // Defaults to false
  });
});
jQuery.fn.handleScroll = (upHandler, downHandler, options) => {
options = options || {};
options.debug = options.debug || false;
/**
* Window object.
*/
const $Window = this;
/**
* States if the document is already loaded.
*/
let isLoaded = false;
jQuery(document).ready(() => {
isLoaded = true;
if (options.debug) {
console.log("[handleScroll] Window loaded");
}
});
let lastScrollTop = 0;
$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;
});
};
"use strict";jQuery.fn.handleScroll=function(a,b,c){c=c||{},c.debug=c.debug||!1;var d,e=!1;jQuery(document).ready(function(){e=!0,c.debug&&console.log("[handleScroll] Window loaded")});var f=0;d.on("scroll",function(){if(e){var g=d.scrollTop();g>f?(c.debug&&console.log("[handleScroll] Window scrolling down"),b()):(c.debug&&console.log("[handleScroll] Window scrolling up"),a()),f=g}})};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment