I am looking to ensure that the scroll bar remains at the bottom each time a user sends or receives a new message.
<script>
$ = jQuery;
var currentID = null;
var chatTimer = null;
var scrolled;
function fetch_data() {
$.ajax({
url: "select.php",
method: "POST",
success: function(data) {
$('#live_data').html(data);
}
});
}
function fetch_chat() {
$.ajax({
url: "fetch_chat.php",
method: "POST",
data: {
id: currentID
},
dataType: "text",
success: function(data) {
$("#chatbox").show();
$('#messages').html(data);
$("div.area").show();
if(!scrolled){
$('#messages').scrollTop($('#messages')[0].scrollHeight);
scrolled=true;
}
}
});
}
$(document).ready(function() {
fetch_data();
$(document).on('click', '.first_name', function() {
scrolled=false;
currentID = $(this).data("id1");
fetch_chat();
});
$("#sub").click(function() {
var text = $("#text").val();
$.post('insert_chat.php', {
id: currentID,
msg: text
}, function(data) {
$("#messages").append(data);
$("#text").val('');
scrolled=false;
setInterval(function() {
fetch_chat();}, 500);
});
});
});
</script>
My objective is to have the scroll bar automatically move to the bottom when a user sends or receives a new message, while still allowing manual scrolling according to the user's preference. I want the fetch_chat() function to be called periodically without affecting the position of the scroll bar - it should remain at the bottom initially, after new messages are sent or received, and be freely scrollable by the user.