AB Tech AB Tech - 2 months ago 9
Ajax Question

how to scroll down a div when ajax is success?

I am developing a chat page, i am using ajax for sending messages and displaying the chat. i want to scroll down the div when the message is send.

this is my div

<div id="messages">
<div>
<img src="">
<label>Sender name</label>
<p>message</p>
</div>
</div>


this is my ajax

$("#btn_post").click(function(e){ //send message button id
$('#ajax_loader').show();
$.ajax({
url:'messages/insert_group_messages',
type: "POST",
data: $('#frmGroupMessage').serialize(),
dataType: "text",
success: function(){
$('#messages').load('group_name/new_messages/'+$('#group_id').val()).fadeIn("slow");
$('#messages').scrollTop($('#messages')[0].scrollHeight); // i tried this to scroll down but its not working.
$('#ajax_loader').hide();
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
e.preventDefault();
});


Message is inserting and showing, but its not scrolling down to show the new message.
can anyone help me.

Answer

Try the following:

$("html,#messages").animate({ scrollTop:$('#messages').prop("scrollHeight"))}, "slow");

Or

$('#messages').load('group_name/new_messages/'+$('#group_id').val()).fadeIn("slow",function(){
    $("html,#messages").animate({ scrollTop:$('#messages').prop("scrollHeight"))}, "slow");
});