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

Asked

Viewed 13,570 times

3

I’m hoping a determined div, possessing the attribute overflow-y:auto, whose height is fixed, is rolled at the end, so an element is added to it.

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

Currently, I can do this easily with the function scrollTop, but I think define the value as 9999999 be it much gambit very inelegant.

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 until the end, without having to use the current method described above?

  • How to know the size of scroll of that div?

2 answers

5


Try to use the scrollHeight, which is a read-only property that measures the content of the element:

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

Source and Fiddle.

Using only jQuery:

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

Fiddle.

  • To be "more jQuery", I can use the prop to not have to access the elements like this?

  • 1

    Yes, it can: $('#div').scrollTop($('#div').prop("scrollHeight"));

  • @Wallacemaxters yes: http://jsfiddle.net/7Lv29w75/1/

  • @Wallacemaxters do not know, I do not see this practice here or in the gringo OS. It is usually placed only in the link and in case the MDN is reliable.

  • Okay, and thanks for the reply :)

  • @Wallacemaxters even so, I put a brief.

  • 2

    This summary already gives a degree. Sometimes a long explanation is ignored by those who are wanting to learn (mainly me)

Show 2 more comments

3

  • The OP actually used animate, good observation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.