Created
December 1, 2015 08:52
-
-
Save kayhadrin/f3b20297d1aaf1d6b360 to your computer and use it in GitHub Desktop.
jQuery plugin to raise custom scroll_vertical and scroll_horizontal events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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