简体   繁体   中英

Upon scrolling to the top of the div, ajax will be loaded

I am currently working on a django chat application which involves using ajax to load the list of chat messages and appending them to one of the divs in my template via jquery (eg chatmsg_div).

Since the chat app will be used by many users, I am required to do pagination for the chat messages which I have been successful in doing so. Now, only the last 20 chat messages in the chatroom will be loaded for the users to see (with the latest message being at the bottom of the div).

However, there is another requirement that I need to do which is to load the chat history (eg previous 20 messages that is in another page) upon scrolling to the top of the chatmsg_div.

My questions will be:

  1. I did some research on google, but could not find any jquery function that allows me to trigger an ajax call upon reaching the top of a specific div. I am pretty new to jquery, so please pardon me even if the answer I am looking for is obvious.
  2. After loading the previous 20 chat messages, I want the div to remain at the position I last scrolled to instead of going to the top of the div

So far, I have tried:

$('#chatmsg_div').scroll(function () { if ($(this).scrollTop() > 100) { debugger; }
});

Thanks in advance for anyone who can answer my questions.

For checking if you need to scroll when a new messages arrived and it's not visible because the user have scrolled to top, you can do:

var shouldScroll = (content.scrollTop + content.offsetHeight >= content.scrollHeight);

Where the content is your DOM container of messages

For detecting if the page is scrolled to the top most:

if (content.scrollTop == 0) {
    // load message history here
}

Now, for implementing auto scroll for new messages and the current scroll is at the bottom of the page, you could do:

if (shouldScroll) {
    content.scrollTop = content.scrollHeight;
}

This should answer all your questions provided that you have enough knowledge to do the other task. No need to use jQuery

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM