I'm appending a new list item and trying to scroll it into view.
Here is my HTML:
<div class="slim-scrollbar">
<ul class="chats">
<li class="out">dynamic text with variable lengths</li>
<li class="in">dynamic text with variable lengths</li>
<li class="in">dynamic text with variable lengths</li>
</ul>
</div>
My current jquery to append an item to the list:
var direction='out';
$('.chats').append('<li class="'+direction+'">'+textVar+'</li>');
My jquery attempt:
$(".chats").animate({
scrollTop: ???
}, 1000);
How do I scroll the new list element into view?
I'm appending a new list item and trying to scroll it into view.
Here is my HTML:
<div class="slim-scrollbar">
<ul class="chats">
<li class="out">dynamic text with variable lengths</li>
<li class="in">dynamic text with variable lengths</li>
<li class="in">dynamic text with variable lengths</li>
</ul>
</div>
My current jquery to append an item to the list:
var direction='out';
$('.chats').append('<li class="'+direction+'">'+textVar+'</li>');
My jquery attempt:
$(".chats").animate({
scrollTop: ???
}, 1000);
How do I scroll the new list element into view?
Share Improve this question edited Jul 19, 2013 at 14:04 Paul asked Jul 19, 2013 at 13:47 PaulPaul 11.8k32 gold badges92 silver badges145 bronze badges 1- What's the code you're using to scroll? – j08691 Commented Jul 19, 2013 at 13:48
5 Answers
Reset to default 4To use your code, this should work:
$('body,html').animate({
scrollTop: $('.chats li:last-child').offset().top + 'px'
}, 1000);
I would suggest a cleaner solution:
var direction = 'out',
lastLi = $("<li/>", {
class: direction,
text: textVar
}).appendTo('.cheats');
$(document).animate({
scrollTop: lastLi.offset().top + 'px'
}, 1000);
Step 1: make sure you've got the scrollTo()
plugin installed.
Step 2: Save the appended object in a temporary variable, then scroll the body (or parent div, if in a scrollable div).
var newelem = $('<li class="'+direction+'">'+textVar+'</li>');
$('.chats').append(newelem);
$('body').scrollTo(newelem);
This may not be an option for you if you really need to use the jQuery animation, but, you could also give your list an id and then use native functionality to get the user to the newly added content.
<ul id="new-stuff" class="chats">
//Append the element and all that good stuff.
location.hash = '#new-stuff';
Assuming your list is inside a wrapper div with some height.
<div id="chatsWrapper" style="height: 200px; overflow:auto;">
<ul class="chats">
<li class="out">dynamic text with variable lengths</li>
<li class="in">dynamic text with variable lengths</li>
<li class="in">dynamic text with variable lengths</li>
</ul>
</div>
$('.chats').append('<li class="'+direction+'">'+textVar+'</li>');
Just animate the wrapper div to an arbitrarily high pixel value:
$('#chatsWrapper').animate({ scrollTop: 10000 }, 'normal');