1

I am working on this demo code. Why am I not able to console log when the top of #c is hitting the bottom of screen?

$(window).scroll(function() {
    var elemTop = $("#c").offset().top;
    var screenBot = $(window).height();
    var currentTop = elemTop - $(window).scrollTop();

 if(currentTop == screenBot) {
        console.log('Bottom of C Hits the View');
    }
    
});
div{  height:500px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a">Section A</div>
<div id="b">Section B</div>
<div id="c">Section C</div>
<div id="d">Section D</div>
halfer
  • 19,824
  • 17
  • 99
  • 186
Mona Coder
  • 6,212
  • 18
  • 66
  • 128
  • 1
    Possible duplicate of [Check if a user has scrolled to the bottom](http://stackoverflow.com/questions/3898130/check-if-a-user-has-scrolled-to-the-bottom) – Heretic Monkey Feb 20 '17 at 17:23

2 Answers2

1

It's because the view scrolls faster than the callback. If you scroll slowly it works

What you need to do is have a lastAt variable that you keep setting, then test for when section c is in between lastAt and currentTop

var lastAt = 0

$(window).scroll(function() {
    var elemTop = $("#c").offset().top;
    var scrollTop = $(window).scrollTop();
    
    //console.log(elemTop, scrollTop, lastAt)
    
    // NOTE: this logic only works when scrolling down
    // you'll need to extend this logic for scrolling up
    if( lastAt < elemTop // havent't hit the c section...
    && scrollTop >= elemTop){ // but we have now
      console.log('Section C in View');
    }
    
    lastAt = scrollTop
    
});
div{  height:500px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a">Section A</div>
<div id="b">Section B</div>
<div id="c">Section C</div>
<div id="d">Section D</div>

NOTE: this logic triggers when the top of "section c" hits the very top of the screen.

Kevin Jantzer
  • 9,215
  • 2
  • 28
  • 52
1

Here is how you can do this. You can check if window.scrollTop + window.height is greater then offsetTop of your element.

$(window).scroll(function() {
  var elemTop = $("#c").offset().top;
  var screenBot = $(window).height();

  if (($(window).scrollTop() + screenBot) > elemTop) {
    $('.result').text('Bottom of C Hits the View')
  } else {
    $('.result').text('') 
  }
});
div {
  height: 700px;
}
.result {
  position: fixed;
  right: 0;
  top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a">Section A</div>
<div id="b">Section B</div>
<div id="c">Section C</div>
<div id="d">Section D</div>
<div class="result"></div>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176