Focus on the last line of the div with scroll

Asked

Viewed 503 times

1

I have a div chat-history attribute-ridden overflow-y:scroll. Through jQuery I insert information into the database and then update to display in the div chat-history. I need that when updating the div via Ajax request, it stay focused on the last line of the scroll bar.

Follows excerpt from the code that updates the div right after entering the data in 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 to

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

But I didn’t get the expected result

  • Well, if the scroll is on . chat-history, you should call the Animate in it. You can post the code so that we can suggest something to you more accurately?

1 answer

2


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

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

scrollHeight: Is an attribute read-only which returns the height of an element content, including unseen content.

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

Follows jsfiddle.

  • Perfect, but can explain the scrollTop and scrollHeight?

  • @Dagobe, I have edited the answer :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.