views:

67

answers:

3

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;
});
A: 

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

Tudorizer
sorry, i actually am using a div instead of a textarea.
BrokeMyLegBiking
@tudorizer `.height()` gives the height of an element, not the `scrollHeight` of it. in your example add some more text to textarea and retry your code
Ninja Dude
+1  A: 

Refer : .scrollTop()

$(function() {
  var height = $('#scroll')[0].scrollHeight;
  $('#scroll').scrollTop(height);
});

You can give it a try here : http://jsbin.com/ucinu

Ninja Dude
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...
john_doe
what exactly you mean ? I don't understand =)
Ninja Dude
A: 

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