JSFiddle - React, Tailwind, and code Playground
HTML
<div class="container">
<div class="messages">
<div class="message">hello 1</div>
<div class="message">hello 2</div>
<div class="message">hello 3</div>
<div class="message">hello 4</div>
<div class="message">hello 5</div>
<div class="message">hello 6 </div>
<div class="message">hello 7</div>
<div class="message">hello 8</div>
<div class="message">hello 9</div>
<div class="message">hello 10</div>
<div class="message">hello 11</div>
<div class="message">hello 12</div>
<div class="message">hello 13</div>
<div class="message">hello 14</div>
<div class="message">hello 15</div>
<div class="message">hello 16</div>
<div class="message">hello 17</div>
<div class="message">hello 18</div>
<div class="message">hello 19</div>
<div class="message">hello 20</div>
<div class="message">hello 21</div>
<div class="message">hello 22</div>
<div class="message">hello 23</div>
<div class="message">hello 24</div>
<div class="message">hello 25</div>
<div class="message">hello 26</div>
<div class="message">hello 27</div>
<div class="message">hello 28</div>
<div class="message">hello 29</div>
<div class="message">hello 30</div>
<div class="message">hello 31</div>
<div class="message">hello 32</div>
<div class="message">hello 33</div>
<div class="message">hello 34</div>
<div class="message">hello 35</div>
<div class="message">hello 36</div>
<div class="message">hello 37</div>
<div class="message">hello 38</div>
<div class="message">hello 39</div>
</div>
<div class="send-message">
<input />
</div>
</div>
CSS
.container {
width: 400px;
height: 87vh;
border: 1px solid #333;
display: flex;
flex-direction: column;
}
.messages {
overflow-y: auto;
height: 100%;
}
.send-message {
width: 100%;
display: flex;
flex-direction: column;
}
JavaScript
window.onload = function(e){
let messages = document.querySelector('.messages')
messages.scrollTop = messages.scrollHeight - messages.clientHeight
bottomScroller(messages);
}
function bottomScroller(scroller) {
let oldScrollTop = scroller.scrollTop
let oldHeight = scroller.clientHeight
scroller.addEventListener('scroll', e => {
console.log(`Scroll detected:
old scroll top = ${oldScrollTop},
old height = ${oldHeight},
new height = ${scroller.clientHeight},
new scroll top = ${scroller.scrollTop}`)
if (oldHeight === scroller.clientHeight)
oldScrollTop = scroller.scrollTop
});
window.addEventListener('resize', e => {
let newScrollTop = oldScrollTop + oldHeight - scroller.clientHeight
console.log(`Resize detected:
old scroll top = ${oldScrollTop},
old height = ${oldHeight},
new height = ${scroller.clientHeight},
new scroll top = ${newScrollTop}`)
scroller.scrollTop = newScrollTop
oldScrollTop = newScrollTop
oldHeight = scroller.clientHeight
});
}