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 scrolls if there are new messages in the div.

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

$("#chat").scrollTop($("#chat")[0].scrollHeight);

  },
});

}, 500);

Is there a way to achieve this without any major ramifications to my code?

Answers


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.


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 div

    if(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.


Need Your Help

How are C++ vtable methods ordered *In Practice*

c++ vtable

In theory, C++ does not have a binary interface, and the order of methods in the vtable is undefined. Change anything about a class's definition and you need to recompile every class that depends ...

ggplot: density plot error

r ggplot2 density-plot

I am trying to plot some density plots overlaid on each other using ggplot