Skip to content

Instantly share code, notes, and snippets.

@CAYdenberg
Created December 16, 2016 23:58
Show Gist options
  • Save CAYdenberg/ade8ac927f1eebf186cd476f80997584 to your computer and use it in GitHub Desktop.
Save CAYdenberg/ade8ac927f1eebf186cd476f80997584 to your computer and use it in GitHub Desktop.
Execute callbacks when element scrolls into view
$.fn.executeWhenVisible = function() {
var _this = this;
var callbacks = [].slice.call(arguments);
var executed = false;
$(window).on('scroll', function onScroll() {
var relativeScroll = $(this).scrollTop() + $(this).height() - _this.offset().top;
if (!executed && relativeScroll > 0) {
executed = true;
callbacks.forEach(function(callback) {
if ($.isFunction(callback)) {
callback.call(_this);
}
});
$(window).off('scroll', onScroll);
}
});
return this;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment