Skip to content

Instantly share code, notes, and snippets.

@PauliusKrutkis
Created May 31, 2017 19:04
Show Gist options
  • Save PauliusKrutkis/484a5964c591889f54041cc231d2130c to your computer and use it in GitHub Desktop.
Save PauliusKrutkis/484a5964c591889f54041cc231d2130c to your computer and use it in GitHub Desktop.
jQuery check if element is visible in view port
function isElementInViewport (el) {
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
(rect.top + rect.height) >= 0 &&
rect.left >= 0 &&
(rect.bottom - rect.height) <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
function onVisibilityChange(el, callback) {
var old_visible;
return function () {
var visible = isElementInViewport(el);
if (visible != old_visible) {
old_visible = visible;
if (typeof callback == 'function') {
callback();
}
}
}
}
function handler() {
$('.elements').each(function(){
console.log(isElementInViewport($(this)))
});
}
$(window).on('DOMContentLoaded load resize scroll', handler);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment