Is there a solution for adding a class to the element in view when scrolling, and removing when out of view? This needs to work for a scrollable div. I have found a few solu
where offset is an element's offset from screen. you should call this (throttles) using the scroll event, the repeatedly check if an element is in view.
function isElementInViewport(el, offset){
var rect = el.getBoundingClientRect();
offset = offset || 0;
return (
rect.top - offset >= 0 &&
rect.left >= 0 &&
rect.bottom + offset <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
onscroll event:// utilizing underscore's `debounce` method
$(window).on('scroll.checkVisibility', _.debounce(check, 200));
function check(){
var visibility = isElementInViewport(element, -100);
if( visibility )
// do something if visisble
}