Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

208
Visualizações
How to keep the scroll position of a div which is updated via AJAX

I am working on a chat module. I am using the setInterval() function to fetch chat history.

I have a scroll bar (shown after the send/receive operation) and then whenever I get a result from the database via AJAX then the scroll bar should stay in the same position, however right now the scroll bar is going to the top of the messages.

How can I handle the AJAX response an keep the message list in a specific position?

var scrollTopPosition = $("div#chat_sc_in").scrollTop();
var scroll_l = $("div#chat_sc_in").scrollLeft();
alert('Height is ' + scrollTopPosition);
alert('Width is ' + scroll_l);

$.ajax({
  type: 'POST',
  url: "<?php echo base_url('Welcome/user_chat_fetch'); ?>",
  data: '',
  success: function(html) {
    $('.user_chat_module').html(html);
    $('.user_chat_module').scrollTop(scrollTopPosition);
  }
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The scrollTop will remain constant after even the height of div increases. The solution is to track the distance between the scrollTop and the bottom of the div when ever the user scrolls and assign the difference of the new height and the calculated value when new content get added.

<script>
     var scrollDifference = 0;
     $("div#chat_sc_in").scroll(event => {
          scrollDifference = event.target.scrollHeight - event.target.scrollTop;
     });

     $.ajax({
           type:'POST',
           url:"<?php echo base_url('Welcome/user_chat_fetch'); ?>",
           data:'',
           success:function(html){
                $('.user_chat_module').html(html);
                var divThatHasScrollBar = $("div#chat_sc_in")[0];
                divThatHasScrollBar.scrollTop = divThatHasScrollBar.scrollHeight - scrollDifference;
           }}); 
</script>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda