grep
grep

Reputation: 4026

Force scrollbar to bottom

I am making a little messaging / chat system that is working nice and fine. The problem is, the <div> which the messages are outputted to does not scroll the way I need it to.

All the new messages are added to the bottom of the div and when more are added and the scrollbar shows up, the scrolling stays at the top of the <div>. I need this to be reversed, so that the scrolling always sticks to the bottom of the <div>.

A good example of what I want would be Steam's chat windows, or even this text input which I am using to fill out the question.

As I would like to avoid jQuery, this has me completely stuck. If you could point me in the correct direction that would be great! I am not sure if HTML and CSS can handle this, or if JavaScript is necessary at all.

Upvotes: 21

Views: 37734

Answers (3)

Assay
Assay

Reputation: 146

For Kotlin I have used the following:

val element = view?.findViewById<ScrollView>(R.id.uidScrollElement)
    element?.smoothScrollTo(0,element.measuredHeight)

Upvotes: 0

Rodan Sotto
Rodan Sotto

Reputation: 51

I think this is a better solution:

element.scrollTop = element.scrollHeight - element.clientHeight;

Upvotes: 5

michaelx386
michaelx386

Reputation: 785

The Javascript code below should keep your div's scrollbar positioned at the bottom like you described:

var objDiv = document.getElementById("divExample");
objDiv.scrollTop = objDiv.scrollHeight;

This solution and more information can be found on the link below: http://web.archive.org/web/20080821211053/http://radio.javaranch.com/pascarello/2005/12/14/1134573598403.html

Upvotes: 29

Related Questions