Wait or check append

2

I have a div that should make a append of some elements and then do a scroll by the end of it.

The problem is that scroll runs before append is finalized. The (generic) code looks 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 can vary and will end up being longer than the time I set in setTimeout and again will not execute second command.

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

What I need is some kind of verification that looks at whether append has been finalized, or something, so the code can continue. And the function with these commands is only called once.

    
asked by anonymous 06.04.2017 / 15:28

2 answers

2

I've found a way to check% from% to append using div , 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 verifies that there has been a size increase of overflow it for verification and the code continues.

    
06.04.2017 / 23:00
3

Unfortunately the append() method does not have a callback to check whether it was done or not, then the alternatives to use setTimeout appear, but as in your case you said that it can vary a lot, try to use the 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><buttonid="append">append</button>
<div id="divUm">divUm</div>
    
06.04.2017 / 16:18