It looks like your HTML code for a simple chat application is partially complete. Below, I'll help you finish and refine your code to make it functional. The code will include the ability to send and display messages in the chat window. Here's the continuation and completion of your code:
html
"data": [
{"user": "Alice", "message": "Hello!"},
{"user": "Bob", "message": "Hi there!"}
]
}
};
document.getElementById('send-button').addEventListener('click', function() {
sendMessage();
});
document.getElementById('message-input').addEventListener('keypress', function(event) {
if (event.key === 'Enter') {
sendMessage();
}
});
function sendMessage() {
const inputField = document.getElementById('message-input');
const messageText = inputField.value.trim();
if (messageText) {
displayMessage(messageText, 'sent');
inputField.value = '';
// Simulating a response from a chatbot
setTimeout(() => {
const botResponse = "You said: " + messageText;
displayMessage(botResponse, 'received');
}, 1000);
}
}
function displayMessage(text, type) {
const messageElement = document.createElement('div');
messageElement.classList.add('message', type);
messageElement.textContent = text;
document.getElementById('chat-messages').appendChild(messageElement);
// Scroll to the bottom of the chat
const chatContainer = document.getElementById('chat-container');
chatContainer.scrollTop = chatContainer.scrollHeight;
}
</script>
</body>
</html>
Explanation of the Code:
HTML Structure:
The chat container, message input, and send button are defined.
The chat-messages div will display current chat messages.
CSS Styling:
Styles are provided for the body, chat container, input, and buttons.
Different styles for sent and received messages enhance usability.
JavaScript:
An event listener is added to the send button.
You can also send messages by pressing the 'Enter' key due to another event listener on the input field.
The sendMessage() function checks if there is text in the input field.
If text is present, it creates a new message element, displays it in the chat, and clears the input field.
Simulated responses from a chatbot are generated for user messages after a brief delay.
The last function, displayMessage(), updates the chat display with the new message and scrolls to the bottom of the chat window.
Usage:
Open this HTML file in your web browser.
Type a message in the input box and either press the "Send" button or hit "Enter" to chat. The bot will send a simple echo response after a second.
Feel free to modify messages or add more features according to your needs!