JQuery - scroll and snap to the bottom of div-ajax if user doesn't scroll

I am trying to scroll to the end of the #chat-feed div with the overflow set to auto and stay there if the user does not scroll this div content. If they scroll back, the div should block at the bottom, and the new content will be displayed at the bottom.

Known Issues: I tried to implement this answer with my code, but I don't know Javascript well enough to make it work. If the content with chat-feed.php above the container, then the scroll remains at the top. It also seems that this answer does not take into account content downloaded from an external file.

Key things: new content should be displayed at the bottom, and the div should be scrolled to the lowest level when new content is loaded, IF users are already scrolling a little. If the user scrolls back, then he should be blocked to the bottom, and new content should be displayed below and be visible.

 <div id="chat-feed" style="height: 200px; width: 300px; overflow: auto;"></div> <script> $(document).ready(function(){ setInterval(function(){ $('#chat-feed').load("chat-feed.php").fadeIn("slow"); }, 1000); }); </script> 

Demo link

+5
source share
1 answer

On the question you contacted, there is a more efficient implementation of fooobar.com/questions/62873 / ....

I have reworked this copyright code below:

 $(document).ready(function() { var out = document.getElementById("chat-feed"); // outer container of messages var c = 0; // used only to make the fake messages different // generate some chatter every second setInterval(function() { //check current scroll position BEFORE message is appended to the container var isScrolledToBottom = checkIfScrolledBottom(); // append new mesage here $('#chat-feed').append("<div>Some new chat..." + c++ + "</div>").fadeIn("slow"); // scroll to bottom if scroll position had been at bottom prior scrollToBottom(isScrolledToBottom); }, 1000); function checkIfScrolledBottom() { // allow for 1px inaccuracy by adding 1 return out.scrollHeight - out.clientHeight <= out.scrollTop + 1; } function scrollToBottom(scrollDown) { if (scrollDown) out.scrollTop = out.scrollHeight - out.clientHeight; } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="chat-feed" style="height: 150px; width: 300px; overflow: auto;"></div> 

UPDATE

The jQuery .load() function removes the associated ( chat-feed ) element and re-adds it. This means that the out variable points to the old deleted item, not the new one. The solution updates the out variable after executing .load() :

 $('#chat-feed').load("chat-feed.php").fadeIn("slow"); out = document.getElementById("chat-feed"); // outer container of messages 
+1
source

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


All Articles