Writing JavaScript for Your ChatBot

  1. 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.

  2. Access DOM Elements: Add the following code to your script.js file:

const chatLog = document.getElementById("chat-log");
const userInput = document.getElementById("user-input");
  1. 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);
}

  1. 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 = "";
  }
});

  1. 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 = "";
  }
});