2

I have an array (which is the offset positions of an unknown number of elements on the page). I want to able to add/remove classes as the users scroll down this number of px on the page.

var offsetPositions = [200,500,700,1000,1100,1500];

$(window).scroll(function(){
  var scrolled  = $(window).scrollTop();
});

The thing is the offset positions in the array are the top and bottom offset positions. So using the example above, the first element's top is at 200px and bottom at 500px. The next has top at 700px and bottom at 1000px. So they are in pairs and there will always be an even number of them.

I need the effect on when scroll position reaches the 1,3,5,7 items in the array and off when it reaches the 2,4,6,8, etc. Like so;

if (scrolled > 200) {
 // add class
}

if (scrolled > 500) {
 // remove class
}

if (scrolled > 700) {
 // add class
}

if (scrolled > 1000) {
 // remove class
}

The end result being the class is there only as the items ar being scrolled passed, not in between.

I can't figure out how to add a for loop for the array while inside the scroll function to give me what I need. I also considered splitting the array into odds and evens, but trying then to compare the two arrays in the way I want was more complicated. I'm just looking for suggestions on which way to go with it, or if I'm overlooking something obvious.

2 Answers2

0

You can try this way to achieve it (by using two dimensional array in JavaScript)

var offsetPositions = [[200,500],[700,1000],[1100,1500]];
offsetPositions.forEach(pairs => {
  if(scrolled > pairs[0]) // add class
  if(scrolled > pairs[1]) // // remove class
}); 

var offsetPositions = [[200,500],[700,1000],[1100,1500]];


$(window).scroll(function(){
  var scrolled  = $(window).scrollTop();
  var index = 0;
  offsetPositions.forEach(pairs => {
    if(scrolled > pairs[0]) console.log("Add class" + index);
    if(scrolled > pairs[1]) console.log("Remove class" + index);
    index += 1;
  }); 
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div style="height: 2000px; overflow-y:scroll;" id="demo">

<div style="height: 200px; background-color:red">height 200</div>

<div style="height: 300px; background-color:green">height 300</div>


<div style="height: 200px; background-color:blue">height 200</div>


<div style="height: 300px; background-color:orange">height 300</div>

</div>
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
0

Determine to add or remove class by index of array

When index is even then add class

When index is odd then remove class

var offsetPositions = [200,500,700,1000,1100,1500];

$(window).scroll(function(){
  var scrolled  = $(window).scrollTop();
  offsetPositions.forEach((v,i)=>{
    if(i%2 == 0 && scrolled > v){
      //Add class
    }else if(scrolled > v){
      //Remove class
    }

  });
});
Ritesh Khandekar
  • 3,885
  • 3
  • 15
  • 30