64

I have a div with a scrollbar on the right when there is a lot of text in it. I tried to use this code to scroll to the bottom of a div when the page loads, but I am not having much luck. How can it be achieved?

Style:

div.messageScrollArea{
    width: 100%;
    max-height: 300px;
    overflow: auto;
}

JavaScript code:

$(document).ready(function () {
    var objDiv = $('.messageScrollArea');
    if (objDiv.length > 0){
        objDiv[0].scrollTop = objDiv[0].scrollHeight;
    }
});
Joshua
  • 6,320
  • 6
  • 45
  • 62
BrokeMyLegBiking
  • 5,898
  • 14
  • 51
  • 66

8 Answers8

113

please refer : .scrollTop(), You can give a try to the solution here : http://jsfiddle.net/y430ovjt/

$(function() {
  var wtf    = $('#scroll');
  var height = wtf[0].scrollHeight;
  wtf.scrollTop(height);
});
 #scroll {
   width: 200px;
   height: 300px;
   overflow-y: scroll;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="scroll">
    <br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/> <center><b>Voila!! You have already reached the bottom :)<b></center>
</div>

Edit : for the people who are looking for a nice little animation with scrolling : http://jsfiddle.net/o98zbx8j

$(function() {
  var height = 0;

  function scroll(height, ele) {
    this.stop().animate({
      scrollTop: height
    }, 1000, function() {
      var dir = height ? "top" : "bottom";
      $(ele).html("scroll to " + dir).attr({
        id: dir
      });
    });
  };
  var wtf = $('#scroll');
  $("#bottom, #top").click(function() {
    height = height < wtf[0].scrollHeight ? wtf[0].scrollHeight : 0;
    scroll.call(wtf, height, this);
  });
});
#scroll {
  width: 300px;
  height: 200px;
  overflow-y: scroll;
}
#bottom,
#top {
  font-size: 12px;
  cursor: pointer;
  min-width: 50px;
  padding: 5px;
  border: 2px solid #0099f9;
  border-radius: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="bottom">scroll to bottom</span>
<br />
<br />
<br />
<div id="scroll">
  <center><b>There's Plenty of Room at the Top, seriously?</b>
  </center>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam at enim dignissim, eleifend eros at, lobortis sem. Mauris vel erat felis. Proin quis convallis neque, quis molestie augue. Vestibulum aliquam elit sit amet venenatis eleifend. Donec dapibus
    mauris ac lorem mattis pulvinar. Curabitur cursus elit commodo tellus bibendum, ut euismod nisi luctus. Pellentesque id magna nunc. Nam luctus nisi sapien, ac porta sem ultrices vitae. Suspendisse aliquet eleifend nunc, in mattis tellus dapibus rutrum.
    Nullam a sem venenatis, suscipit lorem eu, facilisis leo. Nunc eget eleifend magna. Curabitur dictum dui in massa vestibulum sagittis. Mauris sodales neque at tincidunt feugiat. Curabitur iaculis purus nec tortor elementum pulvinar. Donec non mattis
    augue.</p>

  <p>Integer sit amet iaculis nulla. Cras vehicula nunc eu leo aliquet, et convallis erat aliquet. Aenean tempor faucibus justo, porta blandit felis semper at. Maecenas auctor nibh sit amet tellus consectetur, et varius velit iaculis. Phasellus convallis
    lacinia dapibus. Praesent tempus nunc elit, id volutpat tellus sagittis commodo. Vestibulum ultrices quam vel congue viverra. Integer varius diam quis tempor consequat. Integer pulvinar neque lorem, eu lobortis augue pharetra vel. Praesent ornare
    lacus quis nisi fermentum dignissim. Curabitur hendrerit augue eu interdum interdum.</p>

  <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Etiam a ex non dolor rutrum suscipit vitae sit amet nibh. Donec pulvinar odio non ultrices dignissim. Quisque in risus lobortis, accumsan ante et, pellentesque
    erat. Quisque ultricies tortor sed tortor venenatis posuere. Integer convallis nunc ut tellus sagittis, et imperdiet erat volutpat. Sed non maximus augue. Sed mattis ipsum sed sem rutrum, at mollis ligula facilisis. Etiam fringilla hendrerit mi eu
    molestie. Etiam semper feugiat nunc, eu pellentesque metus porta pretium. Duis tempor neque ut libero scelerisque euismod. Vivamus molestie, quam a mattis scelerisque, dolor turpis accumsan quam, a cursus sem quam at ex. Suspendisse congue elit quis
    sem scelerisque commodo.</p>

  <p>Ut eu odio at urna hendrerit ullamcorper. Nulla ut turpis molestie diam aliquet luctus. Curabitur dignissim tellus ut porta sagittis. Vivamus ut erat ut neque consequat interdum. Duis vitae risus eget arcu pulvinar venenatis. Maecenas erat arcu, hendrerit
    id tortor ut, viverra elementum nibh. Nam quis metus sit amet lacus rhoncus porttitor ac non ipsum. Nullam lacus dui, tempus sed elementum ut, venenatis eget ipsum. Quisque blandit maximus enim eu porta.</p>

  <p>Donec mollis diam eros, eu ultrices magna sollicitudin vitae. Nullam quam sapien, elementum a metus nec, facilisis scelerisque nulla. Praesent lobortis nisi ac leo laoreet, quis molestie ipsum porta. Suspendisse aliquet in velit eu ullamcorper. Maecenas
    auctor, mi ut viverra elementum, metus turpis commodo orci, eu commodo erat dolor malesuada arcu. Fusce condimentum augue</p>
  <center><b>Voila!! You have reached the bottom, already! :)</b>
  </center>
</div>
  • 1
    it's not really an issue, but it make's me crazy every time i see this type of waste^^ save $("#scroll") in an variable so you can save the double instantiation of "#scroll". It's not that big thing with an id, but i often see it with really complex selectors too... – Andreas Sep 18 '10 at 20:07
  • 1
    He means you should do something like var scroll = $("#scroll") once, and then reference the scroll variable multiple times. This way jquery doesn't have to search through the dom each time you reference $("#scroll") – thefreeman Nov 26 '12 at 05:01
  • 6
    I'd prefer $wtf, justsaying. – mahemoff Nov 23 '13 at 15:04
  • Hi, this does not work for me for some reason even though its working in the fiddle. Can you please tell me if I am missing out any script links or any other files? Sorry, I'm new to java-scripting. Please let me know. Thanks – James Smith Mar 22 '15 at 04:53
  • Link other than you provided in your answer – James Smith Mar 22 '15 at 05:02
41

No need to calculate the actual height of the contents; you can just scroll down a lot:

$(function () {
  $('.messageScrollArea').scrollTop(1E10);
});
Ruben Verborgh
  • 3,545
  • 2
  • 31
  • 43
  • Does that work in all browsers? If so, then very nice for simplicity. – raider33 Apr 12 '14 at 19:35
  • This works really well. All other code I found worked but with some glitches (not actually going to the very bottom in some cases). Great solution – ctwheels Aug 29 '15 at 14:27
  • It really works perfectly. But how does it work? What is the logic of the parameter `1E10`? I did not find anything related to this in the [jQuery documentation](https://api.jquery.com/scrollTop/#scrollTop2)! I was really curious, someone could explain this? – Fernando Leal Oct 27 '15 at 15:59
  • 1
    @Fernando `1E10` is exponential notation for 100,000,000,000 (the number one followed by 10 zeros)—just a random very large number. The code above means: scroll down _a lot_, with 1e10 being a number that is likely much larger than any contents you would ever put inside of the element. – Ruben Verborgh Oct 27 '15 at 19:27
  • 1
    It works but problem with this method is jquery animations doesn't work with this. – Ali Azhar Aug 25 '16 at 20:54
  • Overkill in it's purest form – Sartheris Stormhammer Oct 14 '16 at 11:41
  • @SartherisStormhammer So this means you have an easier solution? ;-) – Ruben Verborgh Oct 14 '16 at 11:43
  • well I am using the method with .scrollTop(selectorCurrent.prop("scrollHeight") but I just like your overkill method, lol – Sartheris Stormhammer Oct 14 '16 at 11:47
  • @SartherisStormhammer Well, you'll see my “overkill” method is shorter and faster, but choose whichever you like :-) – Ruben Verborgh Oct 14 '16 at 11:52
  • For some reason this method does not work today in M$ Edge :( But it works in Midori :D – OzrenTkalcecKrznaric Jan 09 '17 at 13:46
  • @Thielicious Quite the contrary: having to first calculate height would lead to an extra step. Regardless of what height you set, the browser will _always_ do a bounds check anyway, so this trick uses that bounds check to its advantage. BTW, unless you doing something several times per second (which I guess would not be the case with scrolling all the way down), performance is not an issue. – Ruben Verborgh Jul 07 '17 at 17:36
  • What if it's used for like a chatbox? Where all the users keep flooding the chat, after every content update it fires this jquery since it must always be at bottom to see last message. (just an example) – Thielicious Jul 07 '17 at 17:57
  • 1
    @Thielicious As I wrote, no additional performance impact. However, you don't want to scroll an actual element multiple times per second with _any_ solution. What you're looking for is an infinite scroller such as https://developers.google.com/web/updates/2016/07/infinite-scroller – Ruben Verborgh Jul 08 '17 at 02:38
  • This is the best simplest answer. No need to compute anything. – tgoneil Sep 16 '18 at 03:48
17

Scrolling with animation:

Your DIV:

<div class='messageScrollArea' style='height: 100px;overflow: auto;'>
      Hello World! Hello World! Hello World! Hello World! Hello World! Hello
      Hello World! Hello World! Hello World! Hello World! Hello World! Hello
      Hello World! Hello World! Hello World! Hello World! Hello World! Hello
</div>

jQuery part:

jQuery(document).ready(function(){       
    var $t = $('.messageScrollArea');
    $t.animate({"scrollTop": $('.messageScrollArea')[0].scrollHeight}, "slow");
});

http://jsfiddle.net/3Wx3U/

Naveed
  • 41,517
  • 32
  • 98
  • 131
  • Hi, this does not work for me for some reason even though its working in the fiddle. Can you please tell me if I am missing out any script links or any other files? Sorry, I'm new to java-scripting. Please let me know. Thanks – James Smith Mar 22 '15 at 04:54
  • Thought I'd share my liner. It's very elegant. Thanks. – Andy May 11 '17 at 13:38
  • $('#UI_MESSAGES').animate({"scrollTop": $('#UI_MESSAGES')[0].scrollHeight}, "slow"); – Andy May 11 '17 at 13:38
3
//note: use of stop function to prevent animation build-ups if called repeatedly
//subtracting container height brings scrollTo position to container bottom
scrollUp = function() {
    $("#scroller").stop().animate({ scrollTop: 0 }, "slow");
}

scrollDown = function() {
    var scroller = $('#scroller');
    var height = scroller[0].scrollHeight - $(scroller).height();

    $(scroller).stop().animate({ scrollTop: height }, "slow");
}
mbokil
  • 3,202
  • 30
  • 22
2

Make a jQuery function more flexible.

$.fn.scrollDown=function(){
    let el=$(this)
    el.scrollTop(el[0].scrollHeight)
}

$('div').scrollDown()

https://jsfiddle.net/Thielicious/82ar7db2/

Thielicious
  • 4,122
  • 2
  • 25
  • 35
2

jQuery simple solution, one line, no external lib required :

$("#myDivID").animate({ scrollTop: $('#myDivID')[0].scrollHeight }, 1000);

Change 1000 to another value (this is the duration of the animation).

halfer
  • 19,824
  • 17
  • 99
  • 186
Fifi
  • 3,360
  • 2
  • 27
  • 53
0

$(function() {
  var wtf    = $('#scroll');
  var height = wtf[0].scrollHeight;
  wtf.scrollTop(height);
});
 #scroll {
   width: 200px;
   height: 300px;
   overflow-y: scroll;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="scroll">
    <br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/> <center><b>Voila!! You have already reached the bottom :)<b></center>
</div>
-2

Here's one sample: http://jsfiddle.net/CUUfb/1/

Tudor
  • 4,137
  • 5
  • 38
  • 54