How to do a scroll to the end of a div?

3

I want a given div , which has the attribute overflow-y:auto , whose height is fixed, to be rolled to the end as soon as an element is added to it.

In this case, I need it to roll to the end, because its height is fixed, but the amount of elements inside it is not fixed. That is, once an element is added with a append , I need the scroll to roll to the end of that div .

Currently, I can do this easily with the scrollTop function, but I think that setting the value to 9999999 is too much of a mess.

See something close to what I have:

$(function()
{
  $('#div').animate({scrollTop: 9999999}, 500);
});
#div{
  
   height:150px;
   background: tomato;
   overflow-y: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='div'>
  <li>Conteúdo</li>
  <li>Conteúdo</li>
  <li>Conteúdo</li>
  <li>Conteúdo</li>
  <li>Conteúdo</li>
  <li>Conteúdo</li>
  <li>Conteúdo</li>
  <li>Conteúdo</li>
  <li>Conteúdo</li>
  <li>Conteúdo</li>
  <li>Conteúdo</li>
  <li>Conteúdo</li>
</div>
  • How do I roll this div to the end, without having to use the current method described above?

  • How do I know the size of the scroll of this div?

asked by anonymous 01.09.2015 / 15:00

2 answers

5

Try using scrollHeight , which is a read-only property which gives the measure of the content of the element:

var div = $('#div')[0];
div.scrollTop = div.scrollHeight;

Font and Fiddle >.

Using just jQuery:

var div = $('#div');
div.prop("scrollTop", div.prop("scrollHeight"));

Fiddle .

    
01.09.2015 / 15:07
3

You can do this:

$('#div').animate({scrollTop: $('#div')[0].scrollHeight}, 500);

Pen: link

    
01.09.2015 / 15:09