fantastic-garbanzo/chatroom.HTML
2023-08-28 20:24:43 +02:00

81 lines
2.2 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chatroom</title>
<style>
body {
font-family: Arial, sans-serif;
}
#chatbox {
width: 400px;
height: 300px;
border: 1px solid #ccc;
padding: 10px;
overflow: auto;
}
#message {
width: 100%;
padding: 5px;
}
#send {
margin-top: 5px;
}
</style>
</head>
<body>
<div id="chatbox"></div>
<input type="text" id="message" placeholder="Type your message">
<button id="send">Send</button>
<script>
const chatbox = document.getElementById('chatbox');
const messageInput = document.getElementById('message');
const sendButton = document.getElementById('send');
let messages = [];
sendButton.addEventListener('click', function() {
const message = messageInput.value;
if (message.trim() !== '') {
sendMessage(message);
messageInput.value = '';
}
});
function sendMessage(message) {
// Here, you would typically send the message to your server using an AJAX request
// For demonstration purposes, we'll just add the message locally
messages.push(message);
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
// Replace the URL with the appropriate endpoint on your server
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>
</html>