How to do such a check against a JS array?
-
Good afternoon there is such an array.
var arrayPositions = [493.19998931884766, 916.5999755859375, 1340, 1763.3999633789062, 2186.7999877929688, 2916.2001342773438, 3339.6000366210938, 4068.9999389648438, 4492.400085449219, 4915.799987792969]
10 coordinates.
These are the coordinates of the elements that I get through the each loop.
Jquery has a function like this
$(window).on('scroll', function () { var scroll = $(window).scrollTop(); });
Question
How can I make such a check that if var scroll has values greater than 0 of the element but less than 1, I get the index of 0 of the element. If, for example, the number is more than 4 elements but less than 5, I get its index
And how correct is it to do such a check in Window.Scroll. function. After all, the check will be every time for every pxJavaScript Jace Todd, Jul 21, 2019 -
We hope that the array is sorted.
if (scroll < arrayPositions[0]) return;
let index = arrayPositions.findIndex((el, i, arr) => scroll < arr[i + 1]);Anonymous -
Just go through the array and find the position you want.
$(window).on('scroll', function () {
var scroll = $(window).scrollTop();
let id_ = 0;
for (const z in arrayPositions){
if (z < scroll) {
id_++;
}
}
});
The id_ will store the position in the array.August Hickman
2 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!