Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find element that's on the middle of the visible screen (viewport), on scroll

I need to know if there is a way I can determine if a div is in the center of the screen.

HTML:

<div id="container">
 <div class="box" id="box0">
  text
 </div>
 <div class="box" id="box1">
  text
 </div>

 .....

 <div class="box" id="box100">
  text
 </div>
</div>

Is there a way to determine when a div will be in the center of the visible screen, considering that the page is scrollable? So basically, when the user is scrolling down the page, the div that's in the middle of the visible screen should be selected.

Thanks

like image 708
MichaelD Avatar asked Aug 01 '12 13:08

MichaelD


People also ask

How do you know if an element is visible in the screen during scrolling?

To know whether the element is fully visible in viewport, you will need to check whether top >= 0, and bottom is less than the screen height. In a similar way you can also check for partial visibility, top is less than screen height and bottom >= 0. The Javascript code could be written as : window.

How do you check the element of a viewport?

To find out if the whole element is inside of the viewport we can simply check if the top and left value is bigger or equal to 0, that the right value is less or equal to the viewport height ie window. innerWidth and that the bottom value is less or equal to window. innerHeight.

Is element visible in viewport?

When an element is in the viewport, it appears in the visible part of the screen. If the element is in the viewport, the function returns true . Otherwise, it returns false .

How do I scroll to the center of a div?

height() / 2; Add the half of the height of the element to the scrollTop to scroll to the center of the element.


1 Answers

DEMO PAGE

var findMiddleElement = (function(docElm){
    var viewportHeight = docElm.clientHeight,
        // here i'm using pre-cached DIV elements, but you can use anything you want.
        // Cases where elements are generated dynamically are more CPU intense ofc.
        elements = $('div'); 

    return function(e){
        var middleElement;
        if( e && e.type == 'resize' )
            viewportHeight = docElm.clientHeight;

        elements.each(function(){
            var pos = this.getBoundingClientRect().top;
            // if an element is more or less in the middle of the viewport
            if( pos > viewportHeight/2.5 && pos < viewportHeight/1.5 ){
                middleElement = this;
                return false; // stop iteration 
            }
        });

        console.log(middleElement);
    }
})(document.documentElement);

$(window).on('scroll resize', findMiddleElement);

Another way (for modern browsers only) is to use the intersection API

like image 157
vsync Avatar answered Oct 21 '22 07:10

vsync