Skip to content

Instantly share code, notes, and snippets.

@weblancaster
Last active August 29, 2015 14:06
Show Gist options
  • Save weblancaster/f204c52638d9e156e392 to your computer and use it in GitHub Desktop.
Save weblancaster/f204c52638d9e156e392 to your computer and use it in GitHub Desktop.
javascript snippet for "is element visible"
function isElementInViewport (el) {
//special bonus for those using jQuery
if (el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
function callback () {
//your code here, e.g. console.log('is visible now');
}
function fireIfElementVisible (el, callback) {
return function () {
if ( isElementInViewport(el) ) {
callback();
}
}
}
var handler = fireIfElementVisible (el, callback);
//jQuery
$(window).on('DOMContentLoaded load resize scroll', handler);
/* //non-jQuery
if (window.addEventListener) {
addEventListener('DOMContentLoaded', handler, false);
addEventListener('load', handler, false);
addEventListener('scroll', handler, false);
addEventListener('resize', handler, false);
} else if (window.attachEvent) {
attachEvent('onDOMContentLoaded', handler); // IE9+ :(
attachEvent('onload', handler);
attachEvent('onscroll', handler);
attachEvent('onresize', handler);
}
*/
// http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport/7557433#7557433
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment