"content": "{\"messages\":[{\"text\":\"Hello! How can I help you today?\",\"type\":\"received\"},{\"text\":\"I have a question about your services.\",\"type\":\"sent\"}]}"
}
};
const chatMessages = document.getElementById('chat-messages');
const messageInput = document.getElementById('message-input');
const sendButton = document.getElementById('send-button');
const initializeChat = () => {
const initialMessages = JSON.parse(self.c3_base64files["data.json"].content).messages;
initialMessages.forEach(msg => {
appendMessage(msg.text, msg.type);
});
};
const appendMessage = (text, type) => {
const messageDiv = document.createElement('div');
messageDiv.className = `message ${type}`;
messageDiv.textContent = text;
chatMessages.appendChild(messageDiv);
chatMessages.scrollTop = chatMessages.scrollHeight; // Scroll to the bottom
};
sendButton.addEventListener('click', () => {
const messageText = messageInput.value.trim();
if (messageText) {
appendMessage(messageText, 'sent');
messageInput.value = ''; // Clear the input
// Simulate receiving a response
setTimeout(() => {
appendMessage("Thank you for your message!", 'received'); // This can be replaced with a real response logic
}, 500);
}
});
messageInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
sendButton.click(); // Trigger the send button on Enter key press
}
});
// Initialize the chat with pre-defined messages
initializeChat();
</script>
</body>
</html>
Explanation of the Code:
-
HTML Structure:
- A
div for the chat messages, an input box for typing messages, and a button to send messages.
-
Styling:
- Basic styles for the chat container, messages, sent and received messages.
-
JavaScript Functionality:
self.c3_base64files: This object simulates a static JSON file containing initial chat messages.
initializeChat: This function loads initial messages from the JSON and displays them in the chat.
appendMessage: A function that creates a new message element and appends it to the chat messages container, scrolling to the latest message.
- Event listeners for sending messages by clicking the send button or pressing the Enter key. When a message is sent, it also simulates a received response after a short delay.
This basic chat application provides a foundation and can be expanded with features like real-time communication, message storage, and enhanced styling.