I have an array of values, specifically pixel offsets of a certain type of element.
Let's say they are in an array arrScroll[]
with values [5, 10, 15, 50, 100, 250]
.
If my window scrolls past 5 pixels but not past 10 pixels, I get the index 0. If my window scrolls past 15 pixels but not past 50 pixels, I get the index 2. If it scrolls back below 10 pixels but not below 5, I get the index 0 again.
What I'm trying to do is find a graceful way (instead of a ton of conditionals for each possible range, as the number of ranges can change) to always get the lower of the two indexes of the scroll range that I am in, except at the range 0 to arrScroll[0]
, in which case I pass a different value than the index.
Another example: if I am in the range of arrScroll[3]
and arrScroll[4]
then I will obtain the index 3. Only once I pass the position of the higher index number do I get its index.
This has nothing to do with sorting as the values are already sorted from smallest to greatest. On a scroll event listener, I simply want to obtain the index of the lower of the two values comprising the index.
What would be the best way to organize this so that it can function for an array of arbitrary length?
More complete example:
I have the colors red, blue, and green. I have an array with values [100, 200, 300]
. When my window scrolls past 100 pixels but not past 200 pixels, I will have something like $(element).css('background-color', colorArr[index])
where the color in colorArr[]
at index 0 is red.
Then if the window scrolls past 200, but not past 300, I run the same code snippet, but the index is now 1 and the color is blue.
If I scroll back below 200 pixels but not below 100 pixels, the index is once again 0 and the color passed is red.
This is trivial to create with if statements if the length of the array is known, but I don't know how to do it for an array of arbitrary length.