I'm creating a web chat, but I have a problem: When they send messages, the chat doesn't scroll down. I think you should use JavaScript, but I'm not very experienced with it
This is the HTML code:
<div class="content-dx">
<div id="messages"></div>
<input type="text" id="messageBox" maxlength="100" placeholder="Type your Message here"/>
<button id="send" onclick="Invio()"><i class="fa fa-paper-plane"></i></button>
</div>
"message" is the box that contains the chat, the messages that arrive
CSS code (if it can be useful, but I don't think):
#messages{
background-color:yellow;
margin-bottom: 32px;
height: 86%;
overflow: auto;
text-align: left;
overflow-x: hidden;
margin-left: 5%;
width: 90%;
box-shadow: -1px 4px 28px 0px rgba(0,0,0,0.75);
}
What should I do to make the scroll automatically go down when there are messages?
I tried some codes, they work BUT when I want to go back to reread the messages, it won't let me go.
You can scroll to the bottom of the messages
container with this code
window.scrollTo(0,document.querySelector("#messages").scrollHeight);
You need to tie this code to your event
which controls received messages. I couldn't write that part of the code because your question was missing the event section.
function scrollToBottom(div) {
div.scrollTop = div.scrollHeight
}
const messages = document.querySelector("#messages")
scrollToBottom(messages)
Try this in javascript part:
const messageBox = document.querySelector("#messages");
messageBox.animate({scrollTop:messageBox.scrollHeight});
If this failed, then use this one:
const messageBox = document.querySelector("#messages");
messageBox.animate({scrollTop:messageBox[0].scrollHeight});
One of these will work. Check and give me the feedback whether it works or not.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.