I am creating a chatbox. When the user key in a msg, it suppose to appear immediately at the chatbox. The scroll bar should always scroll to bottom of the chatbox. The below codes did work, but when i try to scroll the bar to the top to view previous msg, it will always be dragged back to the bottom. I am not sure is it because of the setInterval. Any idea how to solve this?
$(function(){
$("#textmsg").keypress(function (e) {
if (((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) && !e.shiftKey){
$('.post').click();
return false;
} else {
return true;
}
});
$(document).on('submit','#discussionForm',function(){
var textmsg = $.trim($("#textmsg").val());
var name = $.trim($("#name").val());
if(textmsg != "" && name!=""){
$.post('inc/postMessages.php', $("#discussionForm").serialize(), function(data){
$(".discussionMessages").html(data);
});
$("#textmsg").val('');
}else{
alert("Please enter some text!");
}
});
setInterval(function(){
getMessages();
},800);
});
function getMessages(){
$.get('inc/getMessages.php', function(data){
var message = $(".discussionMessages");
message.html(data);
message.scrollTop(message[0].scrollHeight);
});
}
I have checked on this post, AJAX Chat Box Scrolling Up Issue but I not really sure how to apply to my code.