I have a list of item divs in the page.
example:
<div data-page='1' class'item' ></div>
<div data-page='1' class'item' ></div>
<div data-page='1' class'item' ></div>
<div data-page='2' class'item' ></div>
<div data-page='2' class'item' ></div>
<div data-page='2' class'item' ></div>
<div data-page='3' class'item' ></div>
<div data-page='3' class'item' ></div>
<div data-page='3' class'item' ></div>
I need to find out the element that is in the most center part of the screen and get its data-page
number.
If all the div are close to the button of the page or not visible because its down the page, I get the top most one because it's closer to the middle, and if all the div are above the middle or not visible because they are at the upper part of the window outside the visible view, I get the bottom most div because it's closer to the middle.
What I've tried (source):
$(".item").sort(function(a,b){
return Math.abs(1 - (($(window).scrollTop()+$(window).height()/2-$(a).height()/2) / $(a).position().top)) -
Math.abs(1 - (($(window).scrollTop()+$(window).height()/2-$(b).height()/2) / $(b).position().top))
})[0].css("background", "red");
The above function didn't work for me, because it highlighted in red a bottom most element.
How can I do that in jQuery and also continuously report the closest one as I vertically scroll the page.
you can use
document.elementFromPoint
giving it the x and y coordinates of the middle of the screenread more about document.elementFromPoint
here is a Codepen example
On the scroll event, you can get the middle of the sreen and then loop the elements you want to check and get each of their positions and find which is closest to the middle of the screen
Here is a working example