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);
}
});
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>