I'm animating a chat. The first function loads the blue messages one after the other each time you press the input field/button. Then a second function shows the grey messages one at a time automatically, after the last blue message appears. But now I want the chat box to scroll down automatically as the grey messages appear.
const myHTMLCollection = document.getElementsByClassName("invisible");
const HTMLElementsArr = [...myHTMLCollection];
function blueMessage() {
if (HTMLElementsArr.length > 0) {
HTMLElementsArr.shift().classList.remove("invisible");
}
if (!HTMLElementsArr.length) {
greyMessage();
}
}
function greyMessage() {
setTimeout(show_second, 1000);
}
function show_second() {
document.getElementById("msg4").style.display = "block";
setTimeout(show_third, 1000);
}
function show_third() {
document.getElementById("msg5").style.display = "block";
setTimeout(show_fourth, 1000);
}
function show_fourth() {
document.getElementById("msg6").style.display = "block";
setTimeout(show_fifth, 1000);
}
function show_fifth() {
document.getElementById("msg7").style.display = "block";
setTimeout(show_sixth, 1000);
}
function show_sixth() {
document.getElementById("msg8").style.display = "block";
setTimeout(show_seventh, 1000);
}
function show_seventh() {
document.getElementById("msg9").style.display = "block";
}
.messages {
height: 500px;
overflow-y: scroll;
}
.invisible {
display: none;
}
<div class="messages" id="chat-window">
<div class="blue invisible" id="msg1">
Hi! I'm looking for an old friend. She attended Martin Grove a few years ago.
</div>
<div class="blue invisible" id="msg2">
Her name is Sam. *insert pic of Sam and MC*
</div>
<div class="blue invisible" id="msg3">
Did you know her or her last name by any chance?
</div>
<div class="grey" id="msg4" style="display: none">Hello there!</div>
<div class="grey" id="msg5" style="display: none">
Unfortunately, I did not have the pleasure of teaching Sam. Her last name and whereabouts are a mystery to me as well.
</div>
<div class="grey" id="msg6" style="display: none">
However, I do know she was in the photography club. I always saw her carrying a camera, always taking pictures.
</div>
<div class="grey" id="msg7" style="display: none">
In fact, I believe she won a contest for one of them.
</div>
<div class="grey" id="msg8" style="display: none">
She’s a super talented girl!
</div>
<div class="grey" id="msg9" style="display: none">
Best of luck on your search. I hope you two are reunited soon!
</div>
</div>
<div class="input" id="chat-button" onClick="blueMessage()"></div>