Create AJAX chat with advanced scroll features. How?

I need some usage examples to accomplish this. I have HTML:

<div id="chatDisplay">
</div>
<input type="text" id="message" /><input type="button" id="send" value="Send" />

Then I have jQuery:

// This function sets up the ajax that posts chat messages to the server.
$(function()
{
     $('#send').click(function ()
     {
          $.ajax(
          {
               url: "chat/postmsg",,
               data: { msg: $('#message').val(); },
               type: "POST",
               success: function (response)
               {
                    // Server sends back formated html to append to chatDisplay.
                    $('#chatDisplay').append(response);
                    //scroll to bottom of chatDisplay
               }
          });
     });
});

// This function periodically checks the server for updates to the chat.
$(function ()
{
     setInterval(function()
     {
          $.ajax(
          {
               url: "chat/getupdates",
               type: "POST",
               success: function (response)
               {
                         // Server sends back any new updates since last check.
                         // Perform scroll and data display functions. Pseudo-code to follow:

                         // If (chatDisplay is scrolled to bottom)
                         // {
                         //     append response to chatDisplay
                         //     scroll to bottom of chatDisplay
                         // }
                         // else if (chatDisplay is scrolled up from bottom by any amount)
                         // {
                         //     append response to chatDisplay, but do not scroll to bottom.
                         // }
               }
          });
     }, 7000);
});

This is just an example of the basic chat features, of course, without server-side code. I need an example of using how to execute what the pseudo code describes. How to determine if the user scrolls to the bottom of the DIV, and how to scroll to the end? I do not want them to jump to the bottom of the DIV if they scroll to see the chat history.

I heard about the JQuery ScrollTo plugin, but you just need some examples.

Thanks in advance!

EDIT: Here is a solution for those interested.

success: function (response)
{
     var elem = $('#chatDisplay');
     var atBottom = (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight());
     $('#chatDisplay').append(response);
     if (atBottom)
          $('#chatDisplay').scrollTop($('#chatDisplay')[0].scrollHeight);
}

For an example of this in action, go to http://www.jsfiddle.net/f4YFL/4/ .

+3
1
+1

Source: https://habr.com/ru/post/1778206/


All Articles