Focus on the last line of div with scroll

1

I have a% div of% with attribute chat-history . Through jQuery I insert information into the database and then refresh to display in the overflow-y:scroll div. I need to update the div via Ajax request, it will focus on the last line of the scroll bar.

Here is an excerpt of the code that updates the div after inserting the data into the database.

function atualiza(){
  $.get(''+ url +'/chat-history', function(result){
  $('.chat-history').html(result);
})
 setTimeout('atualiza()', 3000);
 $('#message-to-send').val('');
 $('#sendMessage').attr("disabled", false);

 //neste momento a div chat-history que está com scroll deve ter seu foco na última linha
}

I tried

$('html, body').animate({ scrollTop: $('.chat-history').offset().bottom }, 300);

But I did not have the expected result

    
asked by anonymous 12.04.2016 / 07:57

1 answer

2

You must pass scrollHeight to scrollTop of animate, and the selector must be in the element that will undergo the animation:

$('.chat-history').animate({ scrollTop: $('.chat-history')[0].scrollHeight }, 300);

scrollHeight : This is a read-only attribute which returns the height of an element content, including non-visible content.

scrollTop : scrolls the element scroll to position defined, from the element passed via selector.

Follow jsfiddle .

    
12.04.2016 / 13:04