Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to scroll down a div when ajax is success?

Tags:

jquery

ajax

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.

like image 945
AB Tech Avatar asked Nov 24 '25 17:11

AB Tech


1 Answers

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");
});
like image 187
Maths RkBala Avatar answered Nov 27 '25 06:11

Maths RkBala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!