How do I keep the scroll position inside a div after updating dynamically with AJAX?

0

I'm building a mini forum, and in it, users can do posts and reply to them.

For the page not to get too long, I put a div with a fixed height and width, and, if the text goes beyond this value, it will add a scrollbar,

The problem is:

I use AJAX to update the answers from time to time, and whenever I update, and it returns the scroll bar to the starting position, I wanted to know if you have how to get the current scrollbar position within div , and when you update with ajax , it will return the bar in that position.

This is the code for AJAX :

<script type="text/javascript">
$(document).ready(function(){
    comeca();
})
var timerR = false;
var timerI = null;
function para(){
    if(timerR)
        clearTimeout(timerI)
    timerR = false;

}
function comeca(){
    para();
    lista();
}
function lista(){
 $.ajax({
        url:"qrTopico.php",
        type: "GET",
        dataType: 'html',
        data: {topico : "<?php echo $topicoGet; ?>"},
        success: function (textStatus){
              $('#respostas').html(textStatus); //mostrando resultado
        }
    })
    timerI = setTimeout("lista()", 10000);//tempo de espera
    timerR = true;
}
</script>
    
asked by anonymous 31.10.2016 / 15:17

2 answers

0

As I can not comment, I will deduce that you are destroying the elements and populating again according to what you return in your Ajax request, in case you are doing so, this behavior of the bar going to the top is to be expected.

I suggest you increment the data that is being updated on elements that are already created, so the scroll bar will keep your current position.

    
31.10.2016 / 20:44
0

You should save the contents of window.scrollTop to a variable before opening the edit field and after saving or reloading with ajax, you can also use it via jQuery (since you used the )

It would look something like:

function atualizaScroll(lastScrollY)
{
    $('#respostas').scrollTop(lastScrollY);
}

function atualizarDados()
{
    var lastScrollY = $('#respostas').scrollTop();

    $.ajax("pagina.php", {
        ... //Dados da requisição aqui
    }).done(function () {
       //Completa a requisição
    }).fail(function () {
       //mostra erro
    }).complete(function () {
       /*
        * Executa mesmo com erro ou sucesso
        * (restaura posição do scroll)
        *
        * Delay é para evitar algo com o tempo da renderização
        */

       setTimeout(atualizaScroll, 10, lastScrollY);
    });
}
    
01.11.2016 / 14:25