Infinite Scroll, insert content when I get up

2

I'm trying to perform a test to make my web with infinite scroll, and upload content as it scrolls down. It happens to me that with the method that I see everywhere, I insert the line when I arrive at the top, I mean I have to go down (it does not do anything), but if I go up at the beginning of everything it inserts it just when I get there.

$(window).scroll(function () {
    if ($(window).scrollTop() + $(window).height() == $(document).height()){ 
        $("body").append('NUEVALINEA<br>');
    }
});

Apparently it happens to me because the result of the IF gives 0, it is taking the same value $ (window) .height () and $ (document) .height (). (And it should not be like that.)
Thanks for the help!
Greetings!

    
asked by Miguel Duran 09.06.2018 в 10:51
source

1 answer

1

Many times the value of $(window).scrollTop() + $(window).height() can be less than 0.5% of $(document).height() so your condition will not be met, to solve this we could add an "offset" and we take advantage so that the elements begin their load before the user reaches the end of the page

$(window).scrollTop() + $(window).height() >= $(document).height() - 50

A tip, it is not advisable to add functions directly to the scroll, in fact some browsers display a warning warning that this may affect performance.

I suggest adding a flag that tells us if it has been scrolled and perform an action depending on the value of this:

var didScroll = false;

// Agregamos un listener al scroll para asignar el valor a la bandera
$(window).scroll(function() {
  didScroll = true;
});

// Declaramos una función que esté llamando cada cierto tiempo para actualizar el estado dependiendo de la bandera
setInterval(function() {
  if (didScroll) {
    if ($(window).scrollTop() + $(window).height() >= ($(document).height() - 50)) {
      $('body').append('<p>Soy un texto nuevo!</p>');
      didScroll = false;

    }
  }
}, 250);
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<h1>Haz scroll :)</h1>
<p>Soy un texto</p>
<p>Soy un texto</p>
<p>Soy un texto</p>
<p>Soy un texto</p>
<p>Soy un texto</p>
<p>Soy un texto</p>
<p>Soy un texto</p>
<p>Soy un texto</p>
<p>Soy un texto</p>
<p>Soy un texto</p>
<p>Soy un texto</p>
<p>Soy un texto</p>
<p>Soy un texto</p>
<p>Soy un texto</p>
<p>Soy un texto</p>
<p>Soy un texto</p>
<p>Soy un texto</p>
<p>Soy un texto</p>
<p>Soy un texto</p>
<p>Soy un texto</p>
<p>Soy un texto</p>
    
answered by 09.06.2018 / 16:36
source