Paul
Paul

Reputation: 11746

How do I scroll to a newly appended list element with jquery

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?

Upvotes: 1

Views: 5949

Answers (5)

insertusernamehere
insertusernamehere

Reputation: 23580

To use your code, this should work:

$('body,html').animate({
    scrollTop: $('.chats li:last-child').offset().top + 'px'
}, 1000);

Upvotes: 4

Abhitalks
Abhitalks

Reputation: 28387

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');

Upvotes: 0

Niccol&#242; Campolungo
Niccol&#242; Campolungo

Reputation: 12042

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);

Upvotes: 1

Justin Helgerson
Justin Helgerson

Reputation: 25521

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';

Upvotes: 0

PaulProgrammer
PaulProgrammer

Reputation: 17630

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);

Upvotes: 0

Related Questions