Question:
Consider the following example I made here:
$("#add").click(function() {
$("#wrap ul").append('<li class="new">Teste</li>');
$("li.new").slideDown('slow', 'easeOutBounce');
});
http://jsfiddle.net/Wagner/4FQCK/5
As you can see when clicking on the add
button jQuery creates a new element li
in my list.. So far so good.. Notice that I defined a max-height
and an overflow: auto
in my wrap
element. The problem is that when I add several elements within my list, the scroll bar of the wrap
is in the middle of it, instead of staying at the bottom
as I would like. So my question is this, how would I do it so that when a new element was added to the scrollbar do not go up (remembering that the user must still have the option to scroll the bar up if he wants to see other items in the list).
Answer:
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);
});
});