Update chatroom.HTML

This commit is contained in:
Dangrainage 2023-08-28 21:06:36 +02:00 committed by GitHub
parent a27ee7f362
commit 2427320f1f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,26 +1,13 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html>
<head> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chatroom</title> <title>Chatroom</title>
<style> <style>
body {
font-family: Arial, sans-serif;
}
#chatbox { #chatbox {
width: 400px; width: 400px;
height: 300px; height: 300px;
border: 1px solid #ccc; border: 1px solid #ccc;
padding: 10px; overflow-y: scroll;
overflow: auto;
}
#message {
width: 100%;
padding: 5px;
}
#send {
margin-top: 5px;
} }
</style> </style>
</head> </head>
@ -34,45 +21,22 @@
const messageInput = document.getElementById('message'); const messageInput = document.getElementById('message');
const sendButton = document.getElementById('send'); const sendButton = document.getElementById('send');
let messages = []; sendButton.addEventListener('click', sendMessage);
sendButton.addEventListener('click', function() { function sendMessage() {
const message = messageInput.value; const message = messageInput.value;
if (message.trim() !== '') { if (message.trim() === '') return;
sendMessage(message);
const messageElement = document.createElement('div');
messageElement.textContent = message;
chatbox.appendChild(messageElement);
// Clear the input field
messageInput.value = ''; messageInput.value = '';
}
});
function sendMessage(message) { // Scroll to the bottom of the chatbox
messages.push(message); chatbox.scrollTop = chatbox.scrollHeight;
updateChatbox();
} }
function updateChatbox() {
chatbox.innerHTML = messages.map(msg => `<div>${msg}</div>`).join('');
chatbox.scrollTop = chatbox.scrollHeight; // Scroll to the bottom
}
messageInput.addEventListener('keyup', function(event) {
if (event.key === 'Enter') {
sendButton.click();
}
});
// Polling with a 3-second interval
setInterval(function() {
// Perform an AJAX request to the server to get new messages
fetch('/getNewMessages')
.then(response => response.json())
.then(data => {
messages = messages.concat(data.messages);
updateChatbox();
})
.catch(error => {
console.error('Error fetching new messages:', error);
});
}, 3000); // 3 seconds interval
</script> </script>
</body> </body>
</html> </html>