67 lines
2.5 KiB
JavaScript
67 lines
2.5 KiB
JavaScript
document.addEventListener('DOMContentLoaded', function () {
|
|
const chatPopup = document.getElementById('chat-popup');
|
|
const chatOpenButton = document.getElementById('chat-open-button');
|
|
const chatCloseButton = document.getElementById('chat-close-button');
|
|
const chatArea = document.getElementById('chat-area');
|
|
const chatForm = document.getElementById('chat-form');
|
|
const chatInput = document.getElementById('chat-input');
|
|
|
|
const toggleChat = () => {
|
|
chatPopup.classList.toggle('show');
|
|
};
|
|
|
|
chatOpenButton.addEventListener('click', toggleChat);
|
|
chatCloseButton.addEventListener('click', toggleChat);
|
|
|
|
const addMessage = (sender, message) => {
|
|
const messageWrapper = document.createElement('div');
|
|
const avatarUrl = sender === 'user' ? 'https://picsum.photos/seed/avatar-user/100/100' : 'https://picsum.photos/seed/avatar-bot/100/100';
|
|
const avatarAlt = sender === 'user' ? 'User Avatar' : 'Chatbot Avatar';
|
|
const messageClass = sender === 'user' ? 'user-message' : 'bot-message';
|
|
|
|
messageWrapper.className = `chat-message ${messageClass}`;
|
|
messageWrapper.innerHTML = `
|
|
<img src="${avatarUrl}" alt="${avatarAlt}" class="avatar">
|
|
<div class="message-content">
|
|
${message}
|
|
</div>
|
|
`;
|
|
chatArea.appendChild(messageWrapper);
|
|
chatArea.scrollTop = chatArea.scrollHeight;
|
|
};
|
|
|
|
chatForm.addEventListener('submit', function (e) {
|
|
e.preventDefault();
|
|
const userMessage = chatInput.value.trim();
|
|
if (userMessage === '') return;
|
|
|
|
addMessage('user', userMessage);
|
|
chatInput.value = '';
|
|
|
|
setTimeout(() => {
|
|
fetch('api/chat.php', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
},
|
|
body: `message=${encodeURIComponent(userMessage)}`
|
|
})
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
if (data.reply) {
|
|
addMessage('bot', data.reply);
|
|
}
|
|
})
|
|
.catch(error => {
|
|
console.error('Error:', error);
|
|
addMessage('bot', 'Sorry, something went wrong. Please try again later.');
|
|
});
|
|
}, 500); // Simulate bot thinking
|
|
});
|
|
|
|
// Initial bot message
|
|
setTimeout(() => {
|
|
addMessage('bot', 'Hello! How can I help you today?');
|
|
}, 1000);
|
|
});
|