How to keep the scroll of the element always in the bottom

11

Consider the following example I made here:

$("#add").click(function() {
    $("#wrap ul").append('<li class="new">Teste</li>');
    $("li.new").slideDown('slow', 'easeOutBounce');
});

link

How can you fix it by clicking on the add button? jQuery creates a new li element in my list .. So far so good .. Note that I set max-height and overflow: auto with%. The problem is that by adding multiple elements within my list, the wrap scroll bar stays in the middle of it, instead of remaining in wrap as I would like .. So my question is this, how would I do to that when a new element is added the scrollbar does not go up (remembering that the user should still have the option to scroll the bar up if he wants to see other items in the list).

    
asked by anonymous 23.02.2014 / 19:55

3 answers

8

You can use this to do the scrol:

    $('#wrap').animate({                   // unsando o jQuery animate para animar o scroll
        scrollTop: $('#wrap ul').height()  // fazer scroll para a posição correspondente à altura do 'ul', o que é o mesmo que dizer scroll até ao fundo
    }, 500);                               // velocidade do scroll em milisegundos

Example

So inside the code where you add a new element you can also have the code I added above to animate a scroll. The final code will be:

$(function () {
    $("#add").click(function () {
        var wrapUl = $("#wrap ul");
        wrapUl.append('<li class="new">Teste</li>');
        // aqui poderia usar o ':last' para evitar aplicar o slideDown a todos os elementos
        // $("li.new:last").slideDown('slow', 'easeOutBounce'); 
        $("li.new").slideDown('slow', 'easeOutBounce');                                      
        $('#wrap').animate({
            scrollTop: wrapUl.height()
        }, 500);
    });
});
    
23.02.2014 / 20:05
6
$(function() {
    $("#add").click(function() {
        $("#wrap ul").append('<li class="new">Teste</li>');
        $("li.new").slideDown('slow', 'easeOutBounce');
        $("#wrap").animate({scrollTop: $('#wrap').prop("scrollHeight")}, 500);
    });
});

jsfiddle

Reference: Append content to div and scroll / animate to bottom

I found the answer in SOEN, and I adapted it for your case, so it would be cool to go there and give it an upvote to the guy, and give it a try!

EDIT: Seeing in the jQuery documentation, it looks like it also supports effects like the "easeOutBounce" you used: animate documentation

    
23.02.2014 / 20:18
1

This line of code helped me a lot, because I tried to keep the scroll at the end of several ways but it was not working! vlw!

$("#wrap").animate({scrollTop: $('#wrap').prop("scrollHeight")}, 500); 
    
26.09.2014 / 21:40