Automatically scroll down chat div

2019-01-18 04:27发布

问题:

I have this code, to load chat

    function getMessages(letter) {
    var div = $("#messages");
    $.get('msg_show.php', function(data) {
        div.html(data);   
    });
}

setInterval(getMessages, 100);

What I have to add, to automatically scroll down #messages div on page load, and again with every new chat post?

This, doesnt work:

    function getMessages(letter) {
    var div = $("#messages");
    $.get('msg_show.php', function(data) {
        div.html(data);
        $('#messages').scrollTop($('#messages')[0].scrollHeight);
    });
}

setInterval(getMessages, 100);

回答1:

Let's review a few useful concepts about scrolling first:

  • scrollHeight: total container size.
  • scrollTop: amount of scroll user has done.
  • clientHeight: amount of container an user sees.

When should you scroll?

  • User has loaded messages for the first time.
  • New messages have arrived and you are at the bottom of the scroll (you don't want to force scroll when the user is scrolling up to read previous messages).

Programmatically that is:

if (firstTime) {
  container.scrollTop = container.scrollHeight;
  firstTime = false;
} else if (container.scrollTop + container.clientHeight === container.scrollHeight) {
  container.scrollTop = container.scrollHeight;
}

Full chat simulator (with JavaScript):

https://jsfiddle.net/apvtL9xa/

const messages = document.getElementById('messages');

function appendMessage() {
	const message = document.getElementsByClassName('message')[0];
  const newMessage = message.cloneNode(true);
  messages.appendChild(newMessage);
}

function getMessages() {
	// Prior to getting your messages.
  shouldScroll = messages.scrollTop + messages.clientHeight === messages.scrollHeight;
  /*
   * Get your messages, we'll just simulate it by appending a new one syncronously.
   */
  appendMessage();
  // After getting your messages.
  if (!shouldScroll) {
    scrollToBottom();
  }
}

function scrollToBottom() {
  messages.scrollTop = messages.scrollHeight;
}

scrollToBottom();

setInterval(getMessages, 100);
#messages {
  height: 200px;
  overflow-y: auto;
}
<div id="messages">
  <div class="message">
    Hello world
  </div>
</div>



回答2:

It's hard to tell without knowing the HTML code, but I'd assume your div doesn't have a height set and/or doesn't allow overflow (e.g. through CSS height: 200px; overflow: auto).

I've made a working sample on jsfiddle: http://jsfiddle.net/hu4zqq4x/

I created some dummy HTML markup inside a div that is a) overflowing and b) has a set height. Scrolling is done through calling the function

function getMessages(letter) {
    var div = $("#messages");
    div.scrollTop(div.prop('scrollHeight'));
}

, in this case once on 'documentReady'.

prop('scrollHeight') will access the value of the property on the first element in the set of matched elements.



回答3:

What you need to do is divide it into two divs. One with overflow set to scroll, and an inner one to hold the text so you can get it's outersize.

<div id="chatdiv">
    <div id="textdiv"/>
</div>

textdiv.html("");
$.each(chatMessages, function (i, e) {
    textdiv.append("<span>" + e + "</span><br/>");
});
chatdiv.scrollTop(textdiv.outerHeight());

You can check out a jsfiddle here: http://jsfiddle.net/xj5c3jcn/1/

Obviously you don't want to rebuild the whole text div each time, so take that with a grain of salt - just an example.



回答4:

    var l = document.getElementsByClassName("chatMessages").length;
    document.getElementsByClassName("chatMessages")[l-1].scrollIntoView();

this should work



回答5:

after append in JQuery,just add this line

<script>
    $("#messages").animate({ scrollTop: 20000000 }, "slow");
</script>


回答6:

Dont have to mix jquery and javascript. Use like this,

function getMessages(letter) {
    var message=$('#messages');
    $.get('msg_show.php', function(data) {
        message.html(data);
        message.scrollTop(message[0].scrollHeight);
    });
}

setInterval(function() {
    getMessages("letter");
}, 100)

Put the scrollTop() inside get() method.

Also you missed a parameter in the getMessage method call..



回答7:

its worked for me try this, let me know if any doubts,

setInterval(function () {
    $("#messages").load("msg_show.php");

   $("#messages").animate({
        scrollTop: $("#messages")[0].scrollHeight}, -500);

}, 1000);


回答8:

I found out this very simple method while experimenting: set the scrollTo to the height of the div.

var myDiv = document.getElementById("myDiv");
window.scrollTo(0, myDiv.innerHeight);


回答9:

if you just scrollheight it will make a problem when user will want to see his previous message. so you need to make something that when new message come only then the code. use jquery latest version. 1.here I checked the height before message loaded. 2. again check the new height. 3. if the height is different only that time it will scroll otherwise it will not scroll. 4. not in the if condition you can put any ringtone or any other feature that you need. that will play when new message will come. thanks

var oldscrollHeight = $("#messages").prop("scrollHeight");
$.get('msg_show.php', function(data) {
    div.html(data);
    var newscrollHeight = $("#messages").prop("scrollHeight"); //Scroll height after the request
    if (newscrollHeight > oldscrollHeight) {
        $("#messages").animate({
            scrollTop: newscrollHeight
        }, 'normal'); //Autoscroll to bottom of div
    }


回答10:

As I am not master in js but I myself write code which check if user is at bottom. If user is at bottom then chat page will automatically scroll with new message. and if user scroll up then page will not auto scroll to bottom..

JS code -

var checkbottom;
jQuery(function($) {
$('.chat_screen').on('scroll', function() {
    var check = $(this).scrollTop() + $(this).innerHeight() >= $(this) 
[0].scrollHeight;
    if(check) {
       checkbottom = "bottom";
    }
    else {
    checkbottom = "nobottom";
    }
})
});
window.setInterval(function(){
if (checkbottom=="bottom") {
var objDiv = document.getElementById("chat_con");
objDiv.scrollTop = objDiv.scrollHeight;
}
}, 500);

html code -

<div id="chat_con" class="chat_screen">
</div>