Wait or check append

Asked

Viewed 121 times

2

I have a div that should make a append of some elements and, after that, should make a scroll until the end of it.

The problem is that the scroll is executed before the append is finished. The (generic) code is like this:

$("div").append(output);
$("div").prop("scrollTop", $("div").prop("scrollHeight"));

If I put the second command inside a setTimeout, this all works, but sometimes the append time may vary and end up being longer than the time I set in setTimeout and again will not execute the second command.

What happens is that since the first command was not complete, the second has no content to give scroll, because the commands follow, without necessarily having finished.

What I need is some kind of verification that observes whether the append was finished, or something, so the code can continue. And the function with these commands is only called once.

2 answers

3

Unfortunately the method append() do not have a callback p/ check whether it was done or not, then arise the alternatives to use setTimeout, but as in your case you said it can vary a lot, try to use the function animate as follows:

$('#append').click(function() {

  $('#divUm').append('<div style="height:800px; border:2px solid red;"></div>');

  $('#divUm').animate({
    scrollTop: $('#divUm').prop("scrollHeight")
  }, 1500);

});
#divUm {
  height: 300px;
  padding: 20px;
  background-color: grey;
  overflow-y: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="append">append</button>
<div id="divUm">divUm</div>

  • Unfortunately this mode did not work. In fact, I had already tried, without success.

  • @Marlonluís if you have how to post more details, the div and the content of the append, can be in jsfiddle.net, we go after the solution.

  • All right, @Mathias, I managed to solve the problem and posted the result below.

  • @Marlonluís Maravilha, I’m glad you were able to answer, I hope my answer will be more useful next time, I even considered suggesting the setInterval but I found it a little dangerous, anyway good that it worked.

2


I figured out a way to do the append for a div who uses overflow, down below:

var intervalo = setInterval(function() {
    // Quando achar algo dentro da div
    if ($("div").children().length > 0) {
        // No meu caso, gostaria que o scroll rolasse até o final
        $("div").prop("scrollTop", $("div").prop("scrollHeight"));
        // Cancela o setInterval
        clearInterval(intervalo);
    }
}, 1);

You can put another value instead of 1 for the range. When it checks that there was the increase in the size of the scroll it for verification and the code continues.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.