For overflow: scroll
to work, you need to explicitly set the divs height. In this case, I used calc
to make it 100vh
and subtracted the height of the form.
For it to scroll from the bottom up, you can use element.scrollTo
and set it to the height of the .chatbox
div each time:
const API_URL = "http://localhost:3000"
const form = document.querySelector("form")
const chatbox = document.querySelector(".chatbox")
const chatInput = document.querySelector(".message-input")
const socket = io.connect(API_URL)
socket.on("chat-message", (data) => {
console.log(data)
appendMessage("other-message", data)
})
socket.on("disconnect", (reason) => {
socket.emit("disconnect", reason)
});
form.addEventListener("submit", e => {
e.preventDefault()
console.log("message: ", chatInput.value)
const message = chatInput.value
appendMessage("message", message)
socket.emit("send-chat-message", message)
form.reset()
chatbox.scrollTo(0, chatbox.scrollHeight)
})
function appendMessage(className, message) {
const div = document.createElement('div')
div.append(message)
div.className = className
chatbox.append(div)
}
.wrapper {
display: grid;
grid-template-columns: 1fr 2fr;
height: 100vh;
width: 100vw;
}
.side-bar {
background-color: blue;
color: gray;
text-align: left;
padding: 20px;
font-size: 50px;
}
.chat-room:hover {
cursor: pointer;
color: white;
}
.messages-container {
display: grid;
grid-template-columns: auto;
grid-template-rows: auto 40px;
}
.chatbox {
height: calc(100vh - 40px);
background-color: black;
border: 1px solid white;
overflow: scroll;
}
.chatbox>div {
border-radius: 15px;
padding: 10px;
margin: 20px;
color: white;
width: fit-content;
max-width: 50%;
}
.message {
background-color: blue;
}
.other-message {
background-color: gray;
}
input {
height: 40px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="wrapper">
<div class="side-bar">
<div class="name">
</div>
<div class="chat-room">
<h3>#chat room 1</h3>
</div>
<div class="chat-room">
<h3>#chat room 2</h3>
</div>
<div class="chat-room">
<h3>#chat room 3</h3>
</div>
<div class="chat-room">
<h3>#lifetime chat</h3>
</div>
</div>
<div class="messages-container">
<!-- Chat messages will be appended here! -->
<div class="chatbox">
</div>
<form>
<input type="text" class="message-input form-control" required name="send-message" placeholder="Send message" aria-label="Recipient's username" aria-describedby="basic-addon2">
</form>
</div>
</div>
<script src="https://cdn.socket.io/socket.io-3.0.1.min.js"></script>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…