71 lines
2.3 KiB
JavaScript
71 lines
2.3 KiB
JavaScript
document.addEventListener('DOMContentLoaded', function () {
|
|
const chatFab = document.getElementById('chat-fab');
|
|
const chatContainer = document.getElementById('chat-container');
|
|
const closeChat = document.getElementById('close-chat');
|
|
const chatForm = document.getElementById('chat-form');
|
|
const chatBody = document.getElementById('chat-body');
|
|
const chatInput = document.getElementById('chat-input');
|
|
|
|
chatFab.addEventListener('click', () => {
|
|
toggleChat();
|
|
});
|
|
|
|
closeChat.addEventListener('click', () => {
|
|
toggleChat();
|
|
});
|
|
|
|
function toggleChat() {
|
|
chatContainer.classList.toggle('open');
|
|
}
|
|
|
|
chatForm.addEventListener('submit', function (e) {
|
|
e.preventDefault();
|
|
const message = chatInput.value.trim();
|
|
if (message === '') return;
|
|
|
|
appendMessage(message, 'user');
|
|
chatInput.value = '';
|
|
chatBody.scrollTop = chatBody.scrollHeight;
|
|
|
|
// Show typing indicator
|
|
appendMessage('...', 'bot', true);
|
|
chatBody.scrollTop = chatBody.scrollHeight;
|
|
|
|
fetch('api/chat.php', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({ message: message }),
|
|
})
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
const typingIndicator = document.querySelector('.typing-indicator');
|
|
if (typingIndicator) {
|
|
typingIndicator.remove();
|
|
}
|
|
appendMessage(data.reply, 'bot');
|
|
chatBody.scrollTop = chatBody.scrollHeight;
|
|
})
|
|
.catch(error => {
|
|
console.error('Error:', error);
|
|
const typingIndicator = document.querySelector('.typing-indicator');
|
|
if (typingIndicator) {
|
|
typingIndicator.remove();
|
|
}
|
|
appendMessage('Sorry, something went wrong.', 'bot');
|
|
chatBody.scrollTop = chatBody.scrollHeight;
|
|
});
|
|
});
|
|
|
|
function appendMessage(text, type, isTyping = false) {
|
|
const messageDiv = document.createElement('div');
|
|
messageDiv.classList.add('chat-message', type);
|
|
if (isTyping) {
|
|
messageDiv.classList.add('typing-indicator');
|
|
}
|
|
messageDiv.textContent = text;
|
|
chatBody.appendChild(messageDiv);
|
|
}
|
|
});
|