forked from tajulafreen/50Projects-HTML-CSS-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
45 lines (40 loc) · 1.48 KB
/
script.js
File metadata and controls
45 lines (40 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
const chatBox = document.getElementById('chatBox');
const chatForm = document.getElementById('chatForm');
const messageInput = document.getElementById('messageInput');
// Display a message in the chat box
const displayMessage = (message, sender) => {
const messageElement = document.createElement('div');
messageElement.classList.add('message', sender);
messageElement.textContent = message;
chatBox.appendChild(messageElement);
chatBox.scrollTop = chatBox.scrollHeight; // Auto-scroll to the bottom
};
// Load messages from local storage
const loadMessages = () => {
const messages = JSON.parse(localStorage.getItem('chatMessages')) || [];
chatBox.innerHTML = '';
messages.forEach(({ user, bot }) => {
displayMessage(user, 'user');
displayMessage(bot, 'bot');
});
};
// Add messages to local storage
const addMessagesToStorage = (userMessage, botReply) => {
const messages = JSON.parse(localStorage.getItem('chatMessages')) || [];
messages.push({ user: userMessage, bot: botReply });
localStorage.setItem('chatMessages', JSON.stringify(messages));
};
// Handle form submission
chatForm.addEventListener('submit', (e) => {
e.preventDefault();
const userMessage = messageInput.value.trim();
if (userMessage) {
const botReply = userMessage; // Echo the user message
displayMessage(userMessage, 'user');
displayMessage(botReply, 'bot');
addMessagesToStorage(userMessage, botReply);
messageInput.value = '';
}
});
// Initialize the app
loadMessages();