Skip to content

Instantly share code, notes, and snippets.

@kayhadrin
Created December 1, 2015 08:52
Show Gist options
  • Save kayhadrin/f3b20297d1aaf1d6b360 to your computer and use it in GitHub Desktop.
Save kayhadrin/f3b20297d1aaf1d6b360 to your computer and use it in GitHub Desktop.
jQuery plugin to raise custom scroll_vertical and scroll_horizontal events
/**
* Simple plugin to track scroll events and trigger a custom jQuery event (scroll_vertical or scroll_horizontal)
* when the corresponding type of scroll has happened.
* Event handlers can receive the original scroll event and the scroll delta as second values.
* e.g. function(jqEvent, scrollEvent, delta)
*
* To stop this, unbind the 'scroll.trackScroll.vertical' or 'scroll.trackScroll.horizontal' event
* @param {string} direction Scroll direction to track
* @return {jQuery}
*/
$.fn.trackScroll = function(direction) {
var curElems = $(this),
customEventName = 'scroll.trackScroll.' + direction;
var getVal = function($elem) {
return direction === 'vertical' ? $elem.scrollTop() : $elem.scrollLeft();
};
return curElems.each(function() {
var $elem = $(this),
prevVal = getVal($elem);
$elem.unbind(customEventName).on(customEventName, function(event) {
var $target = $(event.target),
newVal = getVal($target),
delta = newVal - prevVal;
if (delta) {
$target.trigger('scroll_' + direction, [event, delta]);
}
prevVal = newVal;
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment