I recently developed a live online chat room. I have everything working and secure but I want the div that the messages are stored in to autoscroll to the bottom. I managed to do that with this Javascript:
window.setInterval(function() {
var elem = document.getElementById('messages');
elem.scrollTop = elem.scrollHeight;
}, 100);
But with this, the user can't scroll upwards at all, it is always pushing them back down to the bottom of the div. What I want to happen is if the user is already at the bottom of the div, then when a new message appears it scrolls them to the bottom of the div. BUT if the user is NOT at the bottom of the div then leave them alone until they scroll to the bottom.
Here's the jQuery that updates the div:
window.onload = function(){
setInterval(function(){
$.ajax({
url: "get.php",
type: "GET",
success: function(output){
$("div#messages").html("<p>" + output + "</p>");
}
});
}, 500);
}
Then the div itself is just empty from the start: <div id="messages"></div>
Here's the CSS if you need it:
#messages {
width: 700px;
height: 250px;
border: 2px solid black;
overflow: auto;
-moz-border-radius: 15px;
border-radius: 15px;
}
Both jQuery and Javascript will work for this, I'm not restricted to using one or the other.
If you want to check whether the user has scrolled to the bottom of the page, you can use the scroll() jQuery event. The given code piece takes the top scroll of the window, so how much the page is scrolled down, it adds the height of the visible window and checks if it is equivalent to the height of the document.
innerHeight + window. pageYOffset) >= document. body. offsetHeight) { alert("you're at the bottom of the page"); } };
To detect when a user scrolls to bottom of div with React, we can check if the sum of the scrollTop and clientHeight properties of a scrollable element is equal to the scrollHeight property of the same element.
Summary. Use the getBoundingClientRect() method to get the size of the element and its relative position to the viewport. Compare the position of the element with the viewport height and width to check if the element is visible in the viewport or not.
scrollTop
, at maximum scroll, will be equal to the scrollHeight
minus offsetHeight
of the element. This is because the offsetHeight
is included in the scrollHeight
.
Setting scrollTop
to scrollHeight
works because the browser automatically adjusts the variable to the maximum scroll allowed (scrollHeight - offsetHeight
).
Here's the logic you should use:
if (elem.scrollTop >= (elem.scrollHeight - elem.offsetHeight)) {
elem.scrollTop = elem.scrollHeight;
}
Just slap the if statement around where you're assigning elem.scrollTop
to elem.scrollHeight
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With