Caio Ferrari Caio Ferrari - 4 months ago 8
Javascript Question

Do something 300px after leaves the bottom

I have a code to display something when get 300px before the scroll reaches the bottom! When the bottom is reached, I want to get rid of this message when get 300px after leave the bottom!

It perfectly works when I reach 300px before the bottom, but it doesn't work when I try to scroll 300px back.

document.addEventListener('scroll', function(event) {
var docHeight = $(document).height(); // Document height
var winHeight = $(window).height(); // Window height
var minHeight = docHeight - winHeight; // Real document height
var curHeight = $(window).scrollTop(); // Display the height according to scrolling

$(window).scroll(function() {
//BEFORE
if(curHeight + 300 > minHeight) {
document.getElementById('copyrights').innerHTML = "Welcome to bottom";
}

//AFTER (doesn't work)
if(curHeight - 300 == minHeight - 300) {
document.getElementById('copyrights').innerHTML = "Good bye";
}
});
});

Answer

You'll have to set a flag variable to hold the state of whether you already went to the bottom before or not, or else it will just say goodbye at page load. Also the second check should be if (curHeight <= minHeight - 300). So all in all something like the following:

var scrolledToBottom = false;
document.addEventListener('scroll', function(event) {
  var docHeight = $(document).height();  // Document height
  var winHeight = $(window).height();    // Window height
  var minHeight = docHeight - winHeight; // Real document height
  var curHeight = $(window).scrollTop(); // Display the height according to scrolling

  $(window).scroll(function() {
    //BEFORE
    if(curHeight + 300 > minHeight) {
      document.getElementById('copyrights').innerHTML = "Welcome to bottom";
      scrolledToBottom = true;
    }

    if (scrolledToBottom) {
      //AFTER (doesn't work)
      if (curHeight <= minHeight - 300) {
        document.getElementById('copyrights').innerHTML = "Good bye";
      }
    }
  });
});
Comments