简体   繁体   中英

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?

To use your code, this should work:

$('body,html').animate({
    scrollTop: $('.chats li:last-child').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';

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM