< BACK TO COMPONENTS

Create Your Own Chatbot with HTML, CSS, and JavaScript (Source code)

Faraz

By Faraz -

Learn how to create a chatbot from scratch using HTML, CSS, and JavaScript with our comprehensive guide. Perfect for beginners and intermediate developers!


create your own chatbot with html, css, and javascript.jpg

Chatbots are computer programs designed to simulate human conversation. They have become increasingly popular in recent years, particularly in businesses and customer service environments, as they offer a cost-effective and efficient way to interact with customers. With the rise of AI and natural language processing technology, chatbots are becoming more sophisticated and able to understand and respond to complex user inquiries.


In this guide, we will walk you through the process of creating a chatbot using HTML, CSS, and JavaScript. This guide is aimed at beginners and intermediate developers and designers, who are looking to create a functional chatbot for their website or business. We will provide practical tips and examples for each step of the process, using simple and easy-to-understand language.


By the end of this guide, you will have the skills and knowledge to design and program a chatbot and deploy it on your website or social media platform. So, whether you are a business owner looking to improve customer service, or a developer looking to add a new skill to your toolkit, this guide is for you.


Let's start making a simple chatbot using HTML, CSS, and JavaScript step by step.


Join My Telegram Channel to Download the Projects Source Code: Click Here


Prerequisites:

Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our chatbot.


After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.


The below code is an HTML document that creates a web page with a chatbot interface. The code begins with a <!DOCTYPE html> declaration that tells the browser what version of HTML to use.


The HTML page has a head section that contains metadata about the web page, including the page title, character set, and viewport settings. It also includes links to external resources, such as a CSS stylesheet and some fonts from Google Fonts.


The body section contains the actual content of the web page. It has a div element with the class attribute set to "card", which is a container for the chatbot interface.


The chatbot interface has three sections: the headermessage section, and input section. The header contains a title for the chatbot interface. The message section contains a message from the bot, which is displayed in a div element with the class attribute set to "message" and the id attribute set to "bot". The input section contains an input field for the user to enter their message and a button to send it.


The code also includes a link to a JavaScript file named "script.js", which is responsible for handling the user's input and sending a response back to the bot.


This is the basic structure of our chatbot using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the chatbot is in place, the next step is to add styling to the chatbot using CSS. CSS allows us to control the visual appearance of the website, including things like layout, color, and typography.


Next, we will create our CSS file. In this file, we will use some basic CSS rules to create our chatbot.


The below code is a block of CSS code that defines the styling for a chatbot interface.


The first selector, *, applies the following styles to all elements on the page: the font size is set to 1.3vw (viewport width), and the font family is set to "Epilogue", a sans-serif font.


The HTML selector sets two CSS custom properties using the -- syntax: --scrollbarBG is set to white (#fff) and --thumbBG is set to a light grayish-blue color (#90a4ae).


The body selector sets the background color of the page to a light gray color (#ccc).


The .card selector styles a specific section of the page that contains a chatbot conversation. It sets the height and width of this section to be responsive to the viewport width (vw) and adds a white background color. The chatbot conversation section is positioned 30vw from the left side of the viewport and 5vw from the top. It also has a box-shadow effect that gives it a subtle 3D look.


The .card #header selector styles the header section of the chatbot interface. It sets the height to 5vw and the background color to black (#000), with no padding.


The .card #header h1 selector styles the heading element within the header section. It sets the font size to 2vw, the font family to "Finger Paint" (a cursive font), and the text color to white (#fff). It also adds 1vw of padding around the text.


The .card #message-section selector styles the chatbot message section. It sets the height to 32vw and adds a padding of 0 2.5vw (no padding on the top and bottom, 2.5vw padding on the left and right). It allows the chatbot message section to be scrollable by adding overflow-y: auto. It also sets the width of the scrollbar to 10px and sets the scrollbar color to match the --scrollbarBG and --thumbBG CSS custom properties.


The .card #message-section #bot and .card #message-section #user selectors style the chatbot messages. They set the minimum height to 1.5vw and add a border with a color of #777 (a dark gray color). They also set the background color to white (#fff) and add rounded borders to the bottom right corner. The body .card #message-section #user selector also adds a black border and changes the background color to black (#000), with the text color set to white. The float: right property aligns the user message to the right side of the chatbot interface.


The .card #message-section #user #user-response selector styles the text of the user message. It sets the text color to white (#fff).


The .card #message-section .message selector styles the chatbot messages in general. It sets the text color to black (#000) and adds some padding around the text. It also sets the line-height to 1.2vw, and sets the maximum width to 85% of the container. The word-wrap: break-word property ensures that long words are broken into multiple lines if necessary. The z-index: 2 property ensures that the chatbot messages are positioned above the input section.


The .card #input-section selector styles the chatbot input section. It sets the padding to 0 2.5vw and sets the display property to flex. It also sets the height to 6vw and width to 100%


The #input-section input selector refers to the input field within the #input-section container. The color property sets the text color to black, and min-width sets the minimum width of the input to 0.5% of the viewport width. The outline property removes the default outline around the input field when it is clicked. The height property sets the height of the input field to 5% of the viewport width, and width sets the width to 26% of the viewport width. The border properties set the top, left, and right borders to none, and the bottom border to a solid black line with a thickness of 0.1% of the viewport width.


The .send selector refers to the send button. It has a background of transparent, border of 0, and cursor of pointer, making it look like a clickable button. The flex property specifies the ability for the button to grow or shrink as needed, and margin-left and margin-right properties set the distance between the button and the input field. The padding property sets the padding to 0, and the position property is set to relative. The outline property removes the default outline around the button when it is clicked.


The .send .circle selector refers to a circular element that will contain the icon for the send button. It has a position property set to relative, a width and height property set to 4.8% of the viewport width, and display property set to flex. The align-items and justify-content properties center the icon within the circular element.


The .send .circle i selector refers to the icon element within the .send .circle element. It has a font-size property set to 3% of the viewport width, and margin-left and margin-top properties set to position the icon within the circular element.


This will give our chatbot an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

* {
  font-size: 1.3vw;
  font-family: "Epilogue", sans-serif;
}

html {
  --scrollbarBG: #fff;
  --thumbBG: #90a4ae;
}

body {
  background: #ccc;
}
body .card {
  height: 45vw;
  width: 35vw;
  background-color: white;
  margin-left: 30vw;
  margin-top: 5vw;
  box-shadow: 2vw 2vw 12vw 3vw #ccc;
}
body .card #header {
  height: 5vw;
  background: #000;
  padding: 0vw;
}
body .card #header h1 {
  color: #fff;
  font-size: 2vw;
  font-family: "Finger Paint", cursive;
  padding: 1vw;
}
body .card #message-section::-webkit-scrollbar {
  width: 10px;
}
body .card #message-section {
  height: 32vw;
  padding: 0 2.5vw;
  overflow-y: auto;
  scrollbar-width: thin;
  scrollbar-color: var(--thumbBG) var(--scrollbarBG);
}
body .card #message-section::-webkit-scrollbar-track {
  background: var(--scrollbarBG);
}
body .card #message-section::-webkit-scrollbar-thumb {
  background-color: var(--thumbBG);
  border-radius: 6px;
  border: 3px solid var(--scrollbarBG);
}
body .card #message-section #bot,
body .card #message-section #user {
  position: relative;
  bottom: 0;
  min-height: 1.5vw;
  border: 0.15vw solid #777;
  background-color: #fff;
  border-radius: 0px 1.5vw 1.5vw 1.8vw;
  padding: 1vw;
  margin: 1.5vw 0;
}
body .card #message-section #user {
  border: 1.5px solid #000;
  border-radius: 1.5vw 0vw 1.5vw 1.8vw;
  background-color: #000;
  float: right;
}
body .card #message-section #user #user-response {
  color: #fff;
}
body .card #message-section .message {
  color: #000;
  clear: both;
  line-height: 1.2vw;
  font-size: 1.2vw;
  padding: 8px;
  position: relative;
  margin: 8px 0;
  max-width: 85%;
  word-wrap: break-word;
  z-index: 2;
}
body .card #input-section {
  z-index: 1;
  padding: 0 2.5vw;
  display: flex;
  flex-direction: row;
  align-items: flex-end;
  overflow: hidden;
  height: 6vw;
  width: 100%;
}
body .card #input-section input {
  color: #000;
  min-width: 0.5vw;
  outline: none;
  height: 5vw;
  width: 26vw;
  border-top: none;
  border-left: none;
  border-right: none;
  border-bottom: solid #000 0.1vw;
}
body .card .send {
  background: transparent;
  border: 0;
  cursor: pointer;
  flex: 0 0 auto;
  margin-left: 1.4vw;
  margin-right: 0vw;
  padding: 0;
  position: relative;
  outline: none;
}
body .card .send .circle {
  position: relative;
  width: 4.8vw;
  height: 4.8vw;
  display: flex;
  align-items: center;
  justify-content: center;
}
body .card .send .circle i {
  font-size: 3vw;
  margin-left: -1vw;
  margin-top: 1vw;
} 

Step 3 (JavaScript Code):

Finally, we need to create a chat function in JavaScript.


Below is a simple chatbot code in JavaScript that is designed to communicate with users. It consists of arrays, functions, and event listeners. The arrays "userMessage" and "botReply" contain a list of messages that users might input and responses the chatbot might give.


The "alternative" array contains a list of fallback responses if the chatbot can't find an appropriate response in the "botReply" array.


The "voiceControl" function initializes the speech synthesis API which enables the chatbot to speak the message provided as an argument.


The "sendMessage" function is used to send the input message when the user presses the "Enter" key or clicks the send button.


The "output" function is called when a user sends a message. It compares the user's input message with the messages in the "userMessage" array and generates a response by selecting a message from the corresponding array in "botReply".


The "compare" function checks if the user input message matches with any of the messages in the "userMessage" array, and returns a response from the corresponding array in "botReply". If there is no exact match, it calls the "containMessageCheck" function which checks for partial matches and returns a response from the "alternative" array if no match is found.


The "containMessageCheck" function checks if the input string contains any words from the "userMessage" array and returns a response from the "alternative" array if no match is found.


The code also includes an event listener that waits for the DOM to be loaded, and another event listener that listens for the "Enter" key to be pressed.


Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

const userMessage = [
  ["hi", "hey", "hello"],
  ["sure", "yes", "no"],
  ["are you genious", "are you nerd", "are you intelligent"],
  ["i hate you", "i dont like you"],
  ["how are you", "how is life", "how are things", "how are you doing"],
  ["how is corona", "how is covid 19", "how is covid19 situation"],
  ["what are you doing", "what is going on", "what is up"],
  ["how old are you"],
  ["who are you", "are you human", "are you bot", "are you human or bot"],
  ["who created you", "who made you", "who is your creator"],

  [
    "your name please",
    "your name",
    "may i know your name",
    "what is your name",
    "what call yourself"
  ],
  ["i love you"],
  ["happy", "good", "fun", "wonderful", "fantastic", "cool", "very good"],
  ["bad", "bored", "tired"],
  ["help me", "tell me story", "tell me joke"],
  ["ah", "ok", "okay", "nice", "welcome"],
  ["thanks", "thank you"],
  ["what should i eat today"],
  ["bro"],
  ["what", "why", "how", "where", "when"],
  ["corona", "covid19", "coronavirus"],
  ["you are funny"],
  ["i dont know"],
  ["boring"],
  ["im tired"]
];
const botReply = [
  ["Hello!", "Hi!", "Hey!", "Hi there!"],
  ["Okay"],
  ["Yes I am! "],
  ["I'm sorry about that. But I like you dude."],
  [
    "Fine... how are you?",
    "Pretty well, how are you?",
    "Fantastic, how are you?"
  ],
  ["Getting better. There?", "Somewhat okay!", "Yeah fine. Better stay home!"],

  [
    "Nothing much",
    "About to go to sleep",
    "Can you guess?",
    "I don't know actually"
  ],
  ["I am always young."],
  ["I am just a bot", "I am a bot. What are you?"],
  ["Sabitha Kuppusamy"],
  ["I am nameless", "I don't have a name"],
  ["I love you too", "Me too"],
  ["Have you ever felt bad?", "Glad to hear it"],
  ["Why?", "Why? You shouldn't!", "Try watching TV", "Chat with me."],
  ["What about?", "Once upon a time..."],
  ["Tell me a story", "Tell me a joke", "Tell me about yourself"],
  ["You're welcome"],
  ["Briyani", "Burger", "Sushi", "Pizza"],
  ["Dude!"],
  ["Yes?"],
  ["Please stay home"],
  ["Glad to hear it"],
  ["Say something interesting"],
  ["Sorry for that. Let's chat!"],
  ["Take some rest, Dude!"]
];

const alternative = [
  "Same here, dude.",
  "That's cool! Go on...",
  "Dude...",
  "Ask something else...",
  "Hey, I'm listening..."
];

const synth = window.speechSynthesis;

function voiceControl(string) {
  let u = new SpeechSynthesisUtterance(string);
  u.text = string;
  u.lang = "en-aus";
  u.volume = 1;
  u.rate = 1;
  u.pitch = 1;
  synth.speak(u);
}

function sendMessage() {
  const inputField = document.getElementById("input");
  let input = inputField.value.trim();
  input != "" && output(input);
  inputField.value = "";
}
document.addEventListener("DOMContentLoaded", () => {
  const inputField = document.getElementById("input");
  inputField.addEventListener("keydown", function (e) {
    if (e.code === "Enter") {
      let input = inputField.value.trim();
      input != "" && output(input);
      inputField.value = "";
    }
  });
});

function output(input) {
  let product;

  let text = input.toLowerCase().replace(/[^\w\s\d]/gi, "");

  text = text
    .replace(/[\W_]/g, " ")
    .replace(/ a /g, " ")
    .replace(/i feel /g, "")
    .replace(/whats/g, "what is")
    .replace(/please /g, "")
    .replace(/ please/g, "")
    .trim();

  let comparedText = compare(userMessage, botReply, text);

  product = comparedText
    ? comparedText
    : alternative[Math.floor(Math.random() * alternative.length)];
  addChat(input, product);
}

function compare(triggerArray, replyArray, string) {
  let item;
  for (let x = 0; x < triggerArray.length; x++) {
    for (let y = 0; y < replyArray.length; y++) {
      if (triggerArray[x][y] == string) {
        items = replyArray[x];
        item = items[Math.floor(Math.random() * items.length)];
      }
    }
  }
  //containMessageCheck(string);
  if (item) return item;
  else return containMessageCheck(string);
}

function containMessageCheck(string) {
  let expectedReply = [
    [
      "Good Bye, dude",
      "Bye, See you!",
      "Dude, Bye. Take care of your health in this situation."
    ],
    ["Good Night, dude", "Have a sound sleep", "Sweet dreams"],
    ["Have a pleasant evening!", "Good evening too", "Evening!"],
    ["Good morning, Have a great day!", "Morning, dude!"],
    ["Good Afternoon", "Noon, dude!", "Afternoon, dude!"]
  ];
  let expectedMessage = [
    ["bye", "tc", "take care"],
    ["night", "good night"],
    ["evening", "good evening"],
    ["morning", "good morning"],
    ["noon"]
  ];
  let item;
  for (let x = 0; x < expectedMessage.length; x++) {
    if (expectedMessage[x].includes(string)) {
      items = expectedReply[x];
      item = items[Math.floor(Math.random() * items.length)];
    }
  }
  return item;
}
function addChat(input, product) {
  const mainDiv = document.getElementById("message-section");
  let userDiv = document.createElement("div");
  userDiv.id = "user";
  userDiv.classList.add("message");
  userDiv.innerHTML = `<span id="user-response">${input}</span>`;
  mainDiv.appendChild(userDiv);

  let botDiv = document.createElement("div");
  botDiv.id = "bot";
  botDiv.classList.add("message");
  botDiv.innerHTML = `<span id="bot-response">${product}</span>`;
  mainDiv.appendChild(botDiv);
  var scroll = document.getElementById("message-section");
  scroll.scrollTop = scroll.scrollHeight;
  voiceControl(product);
}

Final Output:

create your own chatbot with html, css, and javascript.gif

Conclusion:

In conclusion, creating a chatbot using HTML, CSS, and JavaScript is an exciting and rewarding project that offers a lot of benefits for businesses and individuals alike. By following the steps outlined in this guide, you can create a functional and engaging chatbot that can interact with users and provide them with helpful information and support.


We started by explaining what chatbots are and their importance in the modern business world. We then walked you through the process of designing the chatbot interface with HTML and CSS, adding animation effects, and programming the chatbot's logic and response system with JavaScript. Finally, we discussed how to deploy your chatbot on your website or social media platform, as well as best practices for chatbot deployment and maintenance.


We hope this guide has provided you with the knowledge and skills to create your own chatbot and explore the possibilities of this exciting technology. Whether you are a business owner looking to improve customer service or a developer looking to expand your skill set, creating a chatbot is a valuable and rewarding experience. So, go ahead and get started on your chatbot project today!

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post