Create a JavaScript File: In your project folder, create a new file named script.js
. This is where we'll write our JavaScript code for the chatbot.
Access DOM Elements: Add the following code to your script.js
file:
const chatLog = document.getElementById("chat-log");
const userInput = document.getElementById("user-input");
Create a Function to Display Messages: We'll create a function that takes a message and appends it to the chat log. Add this code to your script.js
:
function displayMessage(message) {
const messageElement = document.createElement("div");
messageElement.classList.add("message");
messageElement.textContent = message;
chatLog.appendChild(messageElement);
}
Event Listener for User Input: Now, let's listen for when the user presses the "Enter" key after typing a message. Add this code to your script.js
:
userInput.addEventListener("keydown", function(event) {
if (event.key === "Enter" && userInput.value !== "") {
const userMessage = userInput.value;
displayMessage(`You: ${userMessage}`);
// Add bot response here
userInput.value = "";
}
});
Bot Responses: It's time to make the bot respond! Update the code inside the event listener to include bot responses:
const botResponses = [
"Hello there!",
"How can I assist you?",
"I'm here to help!",
"Tell me more."
];
function getBotResponse() {
const randomIndex = Math.floor(Math.random() * botResponses.length);
return botResponses[randomIndex];
}
userInput.addEventListener("keydown", function(event) {
if (event.key === "Enter" && userInput.value !== "") {
const userMessage = userInput.value;
displayMessage(`You: ${userMessage}`);
const botMessage = getBotResponse();
displayMessage(`Bot: ${botMessage}`);
userInput.value = "";
}
});