javascript - Alerting user when div has been scrolled into view -


i trying perform function/alert user when have scrolled down specific div, , whey have scrolled bottom of page. able alert when user has scrolled bottom , top, not sure how specify when user scrolls below fold(to middle section). have following far:

html

<div class="container top">top</div> <div class="container middle">middle</div> <div class="container bottom">bottom</div> 

jquery

$(function () {     var $win = $(window);      $win.scroll(function () {         if ($win.scrolltop() == 0) {             alert("user scrolled top");         } else if ($win.height() + $win.scrolltop() == $(document).height()) {             alert("user scrolled bottom");         }     }); }); 

jsfiddle: link

https://jsfiddle.net/xslx9ojs/1/

i add ids html divs:

<div id="top" class="container top">top</div> <div id="bottom" class="container bottom">bottom</div> 

then add condition detect when bottom div appears in user's screen when scrolls:

$(function () {        var $win = $(window);        $win.scroll(function () {           if ($win.scrolltop() == 0) {               console.log("user scrolled top");           } else if ($win.height() + $win.scrolltop() >= $('#top').height() - 50                      && $win.height() + $win.scrolltop() <= $('#top').height() + 50) {               console.log("transition between 2 divs");           } else if ($win.height() + $win.scrolltop() == $(document).height()) {               console.log("user scrolled bottom");           }       });    }); 

scroll detection not precise cause of little "jumps" mousewheel does. added 100px tolerance. if improve stuff boolean detects if alert bottom div has been given or not function doesn't trigger @ every scroll this:

    [...]     if ($win.scrolltop() == 0) {         //top reached     } else if ($win.height() + $win.scrolltop() >= $('#top').height()) {         //alert! bottom div appeared while scrolling bottom!         //deal boolean     } else if ($win.scrolltop() <= $('#top').height()) {         //alert! bottom div disappeared while scrolling top!         //deal boolean     } else if ($win.height() + $win.scrolltop() == $(document).height()) {         //bottom reached     }     [...] 

Comments