Created
December 16, 2016 23:58
-
-
Save CAYdenberg/ade8ac927f1eebf186cd476f80997584 to your computer and use it in GitHub Desktop.
Execute callbacks when element scrolls into view
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
$.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