2

I have following div structure.

<div id="conversation" class="list-view">
   <div class="conv">
       <div class="msg">Hi 1</div>
       <div class="msg">Hi 2</div>
       <div class="msg">Hi 3</div>
       <div class="msg">Hi 4</div>
       <div class="msg">Hi 5</div>
       <div class="msg">Hi 6</div>
       <div class="msg">Hi 7</div>
       <div class="msg">Hi 8</div>
       <div class="msg">Hi 9</div>
       <div class="msg">Hi 10</div>
   </div>
</div>

Now when i add on ajax submit button new div <div class="msg">Hi 11</div> added at the end of <div class="conv">. i want to scroll down to the bottom new added div.

i have used following but it doesn't work.

$('.conv ').animate({scrollTop: $('.conv')[0].scrollHeight}, 'slow');
$('.conv').scrollTop($('.conv')[0].scrollHeight);

How to scroll down to bottom child div. Position of parent div is fixed.

Jaydeep Mor
  • 1,690
  • 3
  • 21
  • 39
Dhara
  • 1,431
  • 4
  • 29
  • 47

2 Answers2

3

You will need to fix the height of .conv if you want to scroll that. Else, use scroll on the body.

Demo: http://jsfiddle.net/GCu2D/775/

JS:

$(document).ready(function () {
    $('.conv ').animate({
        scrollTop: $('.conv .msg:last-child').position().top
    }, 'slow');
});

CSS:

.conv {
    max-height:100px; //for demo
    overflow:auto;
}
K K
  • 17,794
  • 4
  • 30
  • 39
  • Hi, it scroll to last element but after scrolling again focus to the top div. and is possible to not to div `max-height`? – Dhara Jul 15 '15 at 11:06
  • You'll need to have a height in order to scroll that div. Without the height, scrollbar will not appear and hence no scrolling will happen. So, you will have to set some height on that div. You can scroll back to the top of the div by again following the same login in the callback function of animate. – K K Jul 15 '15 at 11:13
  • Yes. but it is first scroll to bottom and then again to first. i only want to scroll down to bottom. – Dhara Jul 15 '15 at 11:32
  • Then instead of the :last-child in the selector, add the index of the newly added element. Demo : http://jsfiddle.net/GCu2D/778/ – K K Jul 15 '15 at 11:35
0

You can use the following code as:

$('.conv').animate({scrollTop: $('.conv div.msg:last').offset().top});

For the demo : http://jsfiddle.net/GCu2D/776/

sahil gupta
  • 2,339
  • 12
  • 14
  • I would use `position` rather than `offset` – Pete Jul 15 '15 at 10:47
  • You can use that as the .position() method allows us to retrieve the current position of an element relative to the offset parent whereas the offset() method retrieves the current position relative to the document. – sahil gupta Jul 15 '15 at 10:49
  • @sahilgupta, it is the offset parent that OP is wanting to scroll - not the document – Pete Jul 15 '15 at 11:00