Jquery: Scrollbar does not descend to the end of the DIV loaded with the .load request.

1

Hi, SO boys! Is that okay?

I need your help with JQuery so that the scrollbar of the div "content2" scrolls to the end when you click the "Open" button.

Simple, right? The problem is that when I load the content through the .load request, the scroll bar does not run until the end of the div.

When I do the same test with .append, I get success and scrollbar goes down to the end without major problems.

$(function() {
$(".abrir").on('click', function(){

    $('#conteudo1').addClass('d-none');
    $('#conteudo2').removeClass('d-none');

    $( "#conteudo2" ).load( "pagina.html" );

    //Exemplo de uso com .append (Funciona corretamente)
    /*for(var i = 0; i < 1000; i++){            

        $( "#conteudo2" ).append( "<p>Teste</p>" );         

    }*/

    //scroll to last message
    $('#conteudo2').delay(1000).animate ({
      scrollTop: $('#conteudo2')[0].scrollHeight
    });

});

});

HTML

<div id="container">
<div id="conteudo1">
    <div class="abrir">Abrir</div>
</div>

<div id="conteudo2" class="d-none">
    <div id="resultado"></div>
</div>

Note: In the JSFiddle I make available the script with the 2 commands (.append and .load), however I could not load the contents in the .load command, because as this command will load a second page, I could not include that page in the JSFiddle for testing. So it will not work in JSFiddle. But if you try location, you will see that the scroll bar does not go down until the end.

Help me fix the script with the .load command and get the scroll bar down to the end ?! And if possible, explain to me why this happens ?! Why does it work with .append and not with .load, if both load content in div?

JSFiddle link: link

Thank you!

    
asked by anonymous 01.12.2018 / 14:22

1 answer

0

The correct one is to use the callback of the .load() method and to scroll after the request is completed:

$( "#conteudo2" ).load( "pagina.html", function(){
   //scroll to last message
   $('#conteudo2').animate ({
      scrollTop: $('#conteudo2')[0].scrollHeight
   });
} );

In this case you do not even need .delay(1000) , unless, even after the load returns, you want the animate to still wait another 1 second to execute.

.load() is an Ajax request that is asynchronous to the rest of the code. When the request is made, the rest of the code will continue to be executed and when it arrives in the animate, the request has not yet been completed and the .scrollHeight will have the value before .load() .

When doing .append() with for is different because the animate will only be executed after for is finished. for is synchronous.

    
01.12.2018 / 19:26