Get an item closer to the middle of the screen in jQuery

I have a list of item sections on 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, which is located in the very central part of the screen, and get its number data-page.

If all divs are close to the page button or are not visible because it is down the page, I get the top of the page itself because it is closer to the middle, and if all divs are above the middle or not visible because they are at the top the windows are out of visible view, I get the bottom of the div because it is closer to the middle.

What I 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 did not work for me because it was highlighted with the red bottom most of the elements.

jQuery, , .

+4
2

, , , , .

 $(function(){
    $(window).scroll(function(){        
        // get the scroll position of the document + half the window height
        var scrollTop = $(document).scrollTop() + ($(window).height() / 2);
        var positions = [];

        // push each of the items we want to check against to an array with their position and selector
        $('.item').each(function(){
            $(this).removeClass("active");
            positions.push({position:$(this).position().top, element: $(this)});
        });

        var getClosest = closest(positions,scrollTop);
        getClosest.addClass("active"); // the element closest to the middle of the screen
        console.log( getClosest.attr("data-page") );
    });

    // finds the nearest position (from an array of objects) to the specified number
    function closest(array, number) {
        var num = 0;
        for (var i = array.length - 1; i >= 0; i--) {
            if(Math.abs(number - array[i].position) < Math.abs(number - array[num].position)){
                num = i;
            }
        }
        return array[num].element;
    }        
});

+3

document.elementFromPoint, x y

document.addEventListener("scroll", function(){
  let x = window.innerWidth / 2;
  let y = window.innerHeight / 2;
  let element = document.elementFromPoint(x, y);
  let page = element.getAttribute("data-page");
  document.querySelector(".middle") &&   document.querySelector(".middle").classList.remove("middle");
  element.classList.add("middle"); 
})

document.elementFromPoint

Codepen

0

Source: https://habr.com/ru/post/1649008/


All Articles