How to Create a Working Chatbot Using HTML and JavaScript?

Estimated read time 3 min read

Creating a chatbot using HTML and JavaScript involves setting up the user interface using HTML, and using JavaScript to handle the conversation logic and response generation. Here’s an example of how you can create a basic chatbot:

HTML:

<div id="chatbot">
  <div id="conversation"></div>
  <input id="input" type="text" placeholder="Enter your message...">
</div>

JavaScript:

const conversation = document.querySelector("#conversation");
const input = document.querySelector("#input");

input.addEventListener("keydown", (event) => {
  if (event.key === "Enter") {
    const message = input.value;
    appendMessage("user", message);
    input.value = "";
    
    // Handle the user's message and generate a response
    const response = generateResponse(message);
    appendMessage("chatbot", response);
  }
});

function appendMessage(sender, message) {
  const messageElement = document.createElement("div");
  messageElement.innerHTML = `<b>${sender}:</b> ${message}`;
  conversation.appendChild(messageElement);
}

function generateResponse(message) {
  // Implement your chatbot's conversation logic here
  // Use switch statements or if/else statements to handle different inputs
  // and return a response
  
  return "Hello! How can I help you today?";
}

In this example, we have a div with the id attribute set to “chatbot” that contains two elements: a div with the id attribute set to “conversation” to display the chat history, and an input field with the id attribute set to “input” for the user to type their message. We use the querySelector method to select the conversation and input elements.

We add an event listener to the input element that listens for the “keydown” event, and checks if the key that was pressed was the “Enter” key. If it was, we store the input value in the message variable, and call the appendMessage function to display the message in the conversation history. We then clear the input field by setting its value to an empty string.

Next, we call the generateResponse function to handle the user’s message and generate a response. The generateResponse function can implement the chatbot’s conversation logic using switch statements, if/else statements, or other methods, and return a response.

Finally, the appendMessage function takes two arguments: the sender of the message (either “user” or “chatbot”), and the message itself. The function creates a new div element to display the message, sets its inner HTML to display the sender and message, and appends the element to the conversation history.

This is just a basic example, and you can expand on it by adding more sophisticated conversation logic, using APIs to access data, or using machine learning models to generate more natural responses.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply