Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to bottom of div?

I am creating a chat using Ajax requests and I'm trying to get messages div to scroll to the bottom without much luck.

I am wrapping everything in this div:

#scroll {
    height:400px;
    overflow:scroll;
}

Is there a way to keep it scrolled to the bottom by default using JS?

Is there a way to keep it scrolled to the bottom after an ajax request?

like image 950
kush Avatar asked Nov 06 '08 22:11

kush


People also ask

How do I scroll to the bottom of a div?

Use element. scroll() to Scroll to Bottom of Div in JavaScript. You can use element.

How do you automatically scroll to the bottom of a page?

To use you just need to press CTRL+ Left click of your mouse and drag the mouse a bit in the direction you want to scroll the page. For example, if you want to scroll up to the page automatically, click CTRL+ left click and slightly move your mouse upwards, the tool will start scrolling up the page.

How do I scroll a div?

For vertical scrollable bar use the x and y axis. Set the overflow-x:hidden; and overflow-y:auto; that will automatically hide the horizontal scroll bar and present only vertical scrollbar. Here the scroll div will be vertically scrollable.

How do you scroll automatically to the bottom of the div using jquery?

To auto scroll a page from top to bottom we can use scrollTop() and height() method in jquery. In this method pass the document's height in scrollTop method to scroll.


3 Answers

This is much easier if you're using jQuery scrollTop:

$("#mydiv").scrollTop($("#mydiv")[0].scrollHeight);
like image 32
andsien Avatar answered Oct 17 '22 01:10

andsien


Here's what I use on my site:

var objDiv = document.getElementById("your_div");
objDiv.scrollTop = objDiv.scrollHeight;
like image 150
Paige Ruten Avatar answered Oct 17 '22 03:10

Paige Ruten


Try the code below:

const scrollToBottom = (id) => {
    const element = document.getElementById(id);
    element.scrollTop = element.scrollHeight;
}

You can also use Jquery to make the scroll smooth:

const scrollSmoothlyToBottom = (id) => {
    const element = $(`#${id}`);
    element.animate({
        scrollTop: element.prop("scrollHeight")
    }, 500);
}

Here is the demo

Here's how it works:

enter image description here

Ref: scrollTop, scrollHeight, clientHeight

like image 169
Tho Avatar answered Oct 17 '22 03:10

Tho