• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

168
Views
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 3 years ago · Juan Pablo Isaza
1 answers
Answer question

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 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error