Update chatroom.HTML

This commit is contained in:
Dangrainage 2023-08-28 20:11:40 +02:00 committed by GitHub
parent 1402a1a9bb
commit 6328de1e4c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -29,28 +29,26 @@
<input type="text" id="message" placeholder="Type your message"> <input type="text" id="message" placeholder="Type your message">
<button id="send">Send</button> <button id="send">Send</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
<script> <script>
const chatbox = document.getElementById('chatbox'); const chatbox = document.getElementById('chatbox');
const messageInput = document.getElementById('message'); const messageInput = document.getElementById('message');
const sendButton = document.getElementById('send'); const sendButton = document.getElementById('send');
const socket = io(); // Connect to the Socket.io server let messages = [];
sendButton.addEventListener('click', function() { sendButton.addEventListener('click', function() {
const message = messageInput.value; const message = messageInput.value;
if (message.trim() !== '') { if (message.trim() !== '') {
socket.emit('message', message); // Send the message to the server messages.push(message);
updateChatbox();
messageInput.value = ''; messageInput.value = '';
} }
}); });
socket.on('message', function(message) { function updateChatbox() {
const messageElement = document.createElement('div'); chatbox.innerHTML = messages.map(msg => `<div>${msg}</div>`).join('');
messageElement.textContent = message;
chatbox.appendChild(messageElement);
chatbox.scrollTop = chatbox.scrollHeight; // Scroll to the bottom chatbox.scrollTop = chatbox.scrollHeight; // Scroll to the bottom
}); }
messageInput.addEventListener('keyup', function(event) { messageInput.addEventListener('keyup', function(event) {
if (event.key === 'Enter') { if (event.key === 'Enter') {