Skip to content Skip to sidebar Skip to footer

Jquery Chat Application Scroll To Bottom Of Div Only On New Message?

I have picked up this AJAX code from multiple tutorials, but the problem is, when the ajax is called, the div ALWAYS scrolls to the bottom. But I want it so that the div ONLY scrol

Solution 1:

I didn't try it, but I think it has to be something like this... (among other solutions)

var oldscrollHeight = $("#chat")[0].scrollHeight;
                      //Takes the height BEFORE reload the div

$.ajax({
  url: "msg-handle/get-messages.php",
  cache: false,
  data: { room: $("#room").val() },
  success: function(data) { $('#chat').html(data)

    var newscrollHeight = $("#chat")[0].scrollHeight;
                          //Takes the height AFTER reload the divif(newscrollHeight > oldscrollHeight){ //COMPARES
        $("#chat").scrollTop($("#chat")[0].scrollHeight); //Scrolls
    }
},
});

I think You have to put a $("#chat").scrollTop($("#chat")[0].scrollHeight); after the first load of the chat.. just an advise.

Solution 2:

the easiest way would be to let the php script pass a flag when there are new messages in the div. you then just have to put in a check condition for the the scrolling.

another option would be to compare the number of divs in the new .get() result to the previous one and scroll only if there are more divs present in the current.

Post a Comment for "Jquery Chat Application Scroll To Bottom Of Div Only On New Message?"