How to maintain scroll position within a div after dynamically upgrading with AJAX?

Asked

Viewed 1,086 times

0

I’m building a mini forum, and in it, users can do posts and answer them.

For the page not to get too long, I put a div with a fixed height and width, and if the text passes that value, it will add a scroll bar,

The problem is:

I use the AJAX to update the answers from time to time, and whenever I upgrade, div, and when update with the ajax, he return the bar in that position.

This is the code of 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>

2 answers

0

You must record the contents of window.scrollTop in a variable before opening the edit field and after saving or reloading something with ajax, you can also use via jQuery (since you used the tag )

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);
    });
}
  • I tested the code above, but apparently it would work well if it was the "global" scroll of the page, in my case, I would need that behavior to happen with the scroll inside a Div. How would I do that?

  • @kyro23 to yes I understood, my fault, I will edit :)

  • @kyro23 corrected the code and fixed setTimeout too, let me know if it fails ;)

  • @kyro23 Ué, the example did not work? You did not give feedback

  • So I didn’t give back because I spent a boom time looking for the solution to this problem, and from what I understand, it’s a little more complex than just the scroll of the div... Basically I will have to do long pooling to keep an open connection to the server, and check if the result has changed, then yes, when it changes, I display the new information on the screen. The problem is that as I want to run the site on a server, I will have to use web sockets to make this connection, so I’m still studying what would be the best solution. But thanks for the help!

  • @kyro23 but long pooling or ajax are just ways to get the data, the problem is in front-end, it has nothing to do with the source, tells me you either recover the scroll position or you want to force the scroll to always stay in the position of the latest message, equal to online chats/chats?

  • Well, basically it’s the following: The way I did, AJAX will make a request to the server every 10 seconds, and when it finishes this request, it shows all the information on the screen, and when it updates, it happens again and again. But it would be a lot easier if it just updates when there’s new information in the database. That’s where webSockets would come in, because, imagine a server with a thousand users at the same time receiving information from each user every 10 seconds, obviously the server will fall. And I also have plans to make other similar systems on the site.

  • @kyro23 all right I understand, but still this has nothing to do with doubt and if you put that the problem is "which is the best way to communicate front-end with back-end" you will change the meaning of the question. Understand that we are not a forum but a Q&A, the question should be objective, edit it and change the subject would invalidate the answers to my view....

  • ... Something else independent from how gets the data the solution I showed is to solve something with scroll and should work in any situation, now doubt that matters most: you either recover the scroll position or you want to force the scroll to always stay in the position of the latest message, like online chats/chats? @kyro23

  • I understand that the correct thing would be for me to open a new question, because the question here is about scroll and not about webSockets, because my initial problem was just scroll, but I realized that it was not just scroll... To give you an idea of what I’m talking about, this is the site that I’m developing: http://indieworld.atwebpages.com/topico.php?tVkZaRk9WQlJQVDA9 and as you can see, if you touch the scroll inside the div, it goes back to the initial position, precisely because he is upgrading this div, where the right one would only be to increment a new div.

  • And answering your question, the behavior of the scroll that I wish is that it holds itself in the same position that the user left.

  • @kyro23 so I think the answer here works perfectly being ajax or webscoket, must have failed because you put in the wrong order some event. I noticed that the site is still the old script

  • Yes, the idea is that the div has a fixed height and when that height bursts it creates the scroll

  • @kyro23 found the problem, you used multiple repeated Ids, the ID attribute cannot be repeated. You repeated id=answer and id=answers a few times, ID must be unique always

  • The updated code is still on the localhost, but even changing from id to class the result remains the same

  • @kyro23 but not just change a little something or another, it must be a fault of yours, sorry but I’m just trying to guide you to the real problem, I’m just trying to help, it’s not a negative criticism ;)

  • Yes, I understand, but the most logical solution is to change this form of dynamic upgrade, because for what I plan to do would require a lot of the server (which is still a free trial plan), plus that I intend to implement the same technology in other functions, as a chat and a notification system, IE, this way to refresh the page does not fit the demand I need. But still, thanks for helping me :D

Show 12 more comments

0


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

I suggest you make an increment of the data being updated on the elements that are already created, so the scroll bar will maintain its current position.

  • It makes sense... but you could post some code or direct me to some topic that helps me with this?

  • For me to post some code, I need at least your Ajax request code and see the best way to increment the information.

Browser other questions tagged

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