Created
August 14, 2015 12:57
-
-
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.
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
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