Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

202
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda