Length of jQuery doesn't update with append, how to solve?


I'm working on a script that makes it load more records from the database when the user reaches the end of the page scroll.

PHP/SQL is fine, the problem is that jQuery doesn't correctly report the number of occurrences of the finished class on the screen.

I guess the solution is to implement .on somehow, but not Manjo lot of jQuery and I'm hitting me with it.

I explain my code below:

$(document).ready(function() {
  var posicaoAtual = $(window).scrollTop();
  var documentSize = $(document).height();
  var sizeWindow = $(window).height();

  $(window).scroll(function() {
    posicaoAtual = $(window).scrollTop();
    //Até aqui, apenas verifico se o usuário chegou ao final da página. 

    if (posicaoAtual >= (documentSize - sizeWindow)) {
      //Agora que começa o sofrimento

      // Conta a quantidade de vezes que a section.empresa aparece na tela
      var qtdRegistros = $("#empresas section.empresa").length;

      //Variável que utilizo no meu PHP
      var idClientes = $("#idClientes").val();

      // Faz requisição ajax
      $.post("carrega-registros.php", {
        qtdRegistros: qtdRegistros,
        idClientes: idClientes
      }, function(resposta) {
        // Coloca o conteudo na DIV

  $(window).resize(function() {
    posicaoAtual = $(window).scrollTop();
    documentSize = $(document).height();
    sizeWindow = $(window).height();

[EDIT 1]

The entire code works fine. My return is new section class='empresa' within the div id="empresas" .

BUT by var qtdRegistros = $("#empresas section.empresa").length; , the qtdRegistros variable only identifies the number of times the empresa class appears in the original HTML. Disregarding what comes from append . This makes my PHP bring duplicate results, since the qtdRegistros is always the same.

I need to update the length according to the new class that comes in append . But that doesn't happen.

Searching a lot I found something similar implementing the on , but I just couldn't use it. Can anyone show me a way?


What happens is that append does not update the number of elements within the set of the element you are accessing, but the number of children of that element.

To resolve this issue, change the line:

var qtdRegistros = $("#empresas section.empresa").length;

For the following:

var qtdRegistros = $("#empresas").children().length;
Scroll to Top