Skip to content

Instantly share code, notes, and snippets.

@everdimension
Created August 14, 2015 12:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save everdimension/c1858590bc63b5ef00ae to your computer and use it in GitHub Desktop.
Save everdimension/c1858590bc63b5ef00ae to your computer and use it in GitHub Desktop.
Add event listener to the `scroll` event to check if the element is fully visible within the window viewport and do something when it is. Use debounce function to not abuse the cpu.
function debounce (fn, wait) {
var timeout;
return function() {
var cntx = this;
var args = arguments;
clearTimeout(timeout);
timeout = setTimeout(function() {
timeout = null;
fn.apply(cntx, args);
}, wait);
};
}
function isElementInViewport (el) {
var rect = el.getBoundingClientRect();
var cachedDocument = document.documentElement;
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || cachedDocument.clientHeight) &&
rect.right <= (window.innerWidth || cachedDocument.clientWidth)
);
}
var element = document.getElementById('your_element_id'); // cache element
var onScroll = function (evt) {
// element cached from outer scope
if (isElementInViewport(element)) {
// do something, because the element is now fully visible
// YOUR CODE
// now remove event listener
window.removeEventListener(debouncedOnResize);
}
};
var debouncedOnScroll = debounce(onResize, 200);
window.addEventListener('scroll', debouncedOnScroll);
// if element is destroyed or no longer used or needed,
// do now forget to remove event listener
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment