There is a function with which you can check "whether the site scrolled up to the visibility of a particular object":

function isScrolledIntoView(elem) { var docViewTop = $(scroll).scrollTop(); var docViewBottom = docViewTop + $(scroll).height(); var elemTop = $(elem).offset().top; var elemBottom = elemTop + $(elem).height(); return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop)); } 

Suppose isScrolledIntView('footer') returns true if we scroll down and see the footer.

I would like to know how you can change a function and set parameters to it, to determine if we allow * scrolled .testdiv 'a to .li:last-child , which is in it, ie Check the position of the block scrolling, and not the entire window with respect to internal objects?

    1 answer 1

    Since offset() calculates the position of an element with regard to its shift (scrolling), you only need to compare the offset() one element with another:

     function isScrolledIntoView(elem, scroll) { if (scroll === undefined) scroll = window; var docViewTop = $(scroll).offset().top; var docViewBottom = docViewTop + $(scroll).height(); var elemTop = $(elem).offset().top; var elemBottom = elemTop + $(elem).height() return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop)); } $('#container').scroll(function() { console.log(isScrolledIntoView('#elem', '#container')) }) 
     #container { height: 200px; overflow-y: scroll; margin-Top: 50px; } #inner { position: relative; } #elem { position: absolute; top: 300px; background: #ccc } #elem2 { position: absolute; top: 400px; background: #ccc } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> <div id="inner"> <div id="elem">test</div> <div id="elem2">&nbsp;</div> </div> </div> 

    I would like to note that the current condition ((elemBottom <= docViewBottom) && (elemTop >= docViewTop)); executed only if the item is visible entirely.

    • But how can you make half of what you see return true? - turik97
    • swap the elemBottom and elemTop . Then it will turn out that if at least the element is slightly visible - Crantisz