Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to bottom of Div on page load (jQuery)

Tags:

html

jquery

I have a div on my page:

<div id='div1' style='overflow:scroll;overflow-x:hidden;max-height:200px;'></div> 

How can I make the div scroll to the bottom of the div?? Not the page, just the DIV.

like image 760
DobotJr Avatar asked May 08 '12 17:05

DobotJr


People also ask

How do you scroll down to the bottom of a page 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.

How do I make a div scroll to the bottom?

jQuery scroll to the bottom of div set the scrollTop property of a div's JavaScript to the value of scroll height property to scroll to the bottom. ScrollTop and height() methods in jQuery can be used to scroll a page from top to bottom automatically.

How do you scroll to the bottom of the div using JavaScript?

// To scroll to the bottom of a div const theElement = document. getElementById('elementID'); const scrollToBottom = (node) => { node. scrollTop = node. scrollHeight; } scrollToBottom(theElement); // The specified node scrolls to the bottom.

How do I scroll to the bottom of the page?

We can use the window. scrollTo method to scroll to the bottom of the page. window. scrollTo(0, document.


2 Answers

The other solutions here don't actually work for divs with lots of content -- it "maxes out" scrolling down to the height of the div (instead of the height of the content of the div). So they'll work, unless you have more than double the div's height in content inside of it.

Here is the correct version:

$('#div1').scrollTop($('#div1')[0].scrollHeight); 

or jQuery 1.6+ version:

var d = $('#div1'); d.scrollTop(d.prop("scrollHeight")); 

Or animated:

$("#div1").animate({ scrollTop: $('#div1').prop("scrollHeight")}, 1000); 
like image 149
Mike Todd Avatar answered Sep 18 '22 00:09

Mike Todd


All the answers that I can see here, including the currently "accepted" one, is actually wrong in that they set:

scrollTop = scrollHeight 

Whereas the correct approach is to set:

scrollTop = scrollHeight - clientHeight 

In other words:

$('#div1').scrollTop($('#div1')[0].scrollHeight - $('#div1')[0].clientHeight); 

Or animated:

$("#div1").animate({   scrollTop: $('#div1')[0].scrollHeight - $('#div1')[0].clientHeight }, 1000); 
like image 37
patspam Avatar answered Sep 21 '22 00:09

patspam