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,78 +1,42 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html>
<head> <head>
<meta charset="UTF-8"> <title>Chatroom</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <style>
<title>Chatroom</title> #chatbox {
<style> width: 400px;
body { height: 300px;
font-family: Arial, sans-serif; border: 1px solid #ccc;
} overflow-y: scroll;
#chatbox { }
width: 400px; </style>
height: 300px;
border: 1px solid #ccc;
padding: 10px;
overflow: auto;
}
#message {
width: 100%;
padding: 5px;
}
#send {
margin-top: 5px;
}
</style>
</head> </head>
<body> <body>
<div id="chatbox"></div> <div id="chatbox"></div>
<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> <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');
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);
messageInput.value = '';
}
});
function sendMessage(message) { const messageElement = document.createElement('div');
messages.push(message); messageElement.textContent = message;
updateChatbox(); chatbox.appendChild(messageElement);
}
function updateChatbox() { // Clear the input field
chatbox.innerHTML = messages.map(msg => `<div>${msg}</div>`).join(''); messageInput.value = '';
chatbox.scrollTop = chatbox.scrollHeight; // Scroll to the bottom
}
messageInput.addEventListener('keyup', function(event) { // Scroll to the bottom of the chatbox
if (event.key === 'Enter') { chatbox.scrollTop = chatbox.scrollHeight;
sendButton.click(); }
} </script>
});
// 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>
</body> </body>
</html> </html>