|
| 1 | +const chatBox = document.getElementById('chatBox'); |
| 2 | +const chatForm = document.getElementById('chatForm'); |
| 3 | +const messageInput = document.getElementById('messageInput'); |
| 4 | + |
| 5 | +// Display a message in the chat box |
| 6 | +const displayMessage = (message, sender) => { |
| 7 | + const messageElement = document.createElement('div'); |
| 8 | + messageElement.classList.add('message', sender); |
| 9 | + messageElement.textContent = message; |
| 10 | + chatBox.appendChild(messageElement); |
| 11 | + chatBox.scrollTop = chatBox.scrollHeight; // Auto-scroll to the bottom |
| 12 | +}; |
| 13 | + |
| 14 | +// Load messages from local storage |
| 15 | +const loadMessages = () => { |
| 16 | + const messages = JSON.parse(localStorage.getItem('chatMessages')) || []; |
| 17 | + chatBox.innerHTML = ''; |
| 18 | + messages.forEach(({ user, bot }) => { |
| 19 | + displayMessage(user, 'user'); |
| 20 | + displayMessage(bot, 'bot'); |
| 21 | + }); |
| 22 | +}; |
| 23 | + |
| 24 | +// Add messages to local storage |
| 25 | +const addMessagesToStorage = (userMessage, botReply) => { |
| 26 | + const messages = JSON.parse(localStorage.getItem('chatMessages')) || []; |
| 27 | + messages.push({ user: userMessage, bot: botReply }); |
| 28 | + localStorage.setItem('chatMessages', JSON.stringify(messages)); |
| 29 | +}; |
| 30 | + |
| 31 | +// Handle form submission |
| 32 | +chatForm.addEventListener('submit', (e) => { |
| 33 | + e.preventDefault(); |
| 34 | + const userMessage = messageInput.value.trim(); |
| 35 | + if (userMessage) { |
| 36 | + const botReply = userMessage; // Echo the user message |
| 37 | + displayMessage(userMessage, 'user'); |
| 38 | + displayMessage(botReply, 'bot'); |
| 39 | + addMessagesToStorage(userMessage, botReply); |
| 40 | + messageInput.value = ''; |
| 41 | + } |
| 42 | +}); |
| 43 | + |
| 44 | +// Initialize the app |
| 45 | +loadMessages(); |
0 commit comments