I have created an array of elements that I would like to continually loop through on window scroll checking if element is visible and if so setting it as active and then I would like to remove this element from the array eventually doing a check to see if the array is empty in order to unbind the scroll event.
At the moment I'm having some difficulty knowing what way I should remove this element? I'm currently using:
var index = innerItems.index($thisEl.index());
innerItems.splice(index, 1);
This however seems to screw up the function I'm using to check the elements in view and my array length never seems to change.
Can anyone recommend how I can achieve my target of being able to remove each element as it becomes active until my array is empty and unbind the scroll event? Also if anyone can offer any improvements that would be amazing.
Codepen http://codepen.io/styler/pen/zDJrx
JS
var $mainContainer = $('.main-container'),
innerItems = $mainContainer.children();
function isElementInViewport (el) {
//special bonus for those using jQuery
if (typeof jQuery === "function" && 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 init() {
itemChecker();
}
init();
$(window).on('scroll.windowScroll', itemChecker);
function itemChecker() {
innerItems.each(function(i, element) {
console.log('Index', i);
console.log('Element', element);
var $thisEl = $(element);
// if isElementInViewport then add class is-active and remove from innerItems array
var inView = isElementInViewport(element);
if( inView ) {
$thisEl.addClass('is-active');
// Remove each element as it becomes ready/in view
var index = innerItems.index($thisEl.index());
innerItems.splice(index, 1);
}
console.log('innerItems length', innerItems.length);
if( innerItems.length === 0 ) {
$(window).off('scroll.windowScroll');
}
});
}