Open In App

Create Working Chatbot in HTML CSS & JavaScript

Last Updated : 08 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A working chatbot is an application that can be developed to answer every sort of question. Chatbot is a web interface that can answer every question in the most human possible way. It is based on the technology of artificial intelligence. In this article, we will be learning how to create a working chatbot using HTML, CSS & Javascript by using OpenAI’s API Key.

Screenshot-(370)

Chatbot Preview

Prerequisites:

Approach:

  • Create a directory with 3 files & one cross icon : index.html, style.css & script.js. Add basic boiler plate code and create a container of a chatbot with a cross icon to remove the chatbot after use, two paragraphs, one for incoming messages, and the other one for outgoing messages. Also create a send button to send a message.
  • Create styling for the containers & also add a class of error where the incoming message’s container turns light red in color to show there is an error in API Key.
  • Create a free OpenAI Key using the official website. Create an account, or login onto your existing account and go to API Documentation. Select the option to view secret API Keys, and create a new API Key. Store it for future usage.
  • Copy the API Key in the script file and generate a response using fetch method. Add the required headers and add the answer or response to the message if the API key works successfully. If not generate an error message stating that an error occurred. Finally, whatsoever message is created, scroll the chatbot container downwards.
  • The send button handles the sending of messages.
  • On clicking the cross button, the chatbot container disappears and a final thanks message is received.

Project Structure:

Screenshot-(369)

Project Structure

Example: This example demonstrate the working of Chatbot by giving response of the user queries and it shows an error when there is an error in the API key.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>ChatBot</title>
    <link rel="stylesheet" href="style.css">
</head>
 
<body>
    <div class="chatBot">
        <header>
            <h2>ChatBot</h2>
            <span alt="Close"
                  id="cross"
                  onclick="cancel()">X</span>
        </header>
        <ul class="chatbox">
            <li class="chat-incoming chat">
                <p>Hey! How can I assist you today?</p>
            </li>
        </ul>
        <div class="chat-input">
            <textarea rows="0" cols="17"
                      placeholder="Enter a message..."></textarea>
            <button id="sendBTN">Send</button>
        </div>
    </div>
    <script src="script.js" defer></script>
</body>
 
</html>


CSS




/*style.css*/
 
@import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap');
 
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
 
body {
  font-family: "Poppins", sans-serif;
  font-weight: 400;
  font-style: normal;
  background-color: #f7f7f7;
}
 
.chatBot {
  border: 3px solid #2F8D46;
  border-radius: 10px;
  margin: 50px auto;
  overflow: hidden;
  width: 500px;
  overflow-y: clip;
  height: 600px;
  background: rgb(255, 255, 255) url(gfg-gg-logo.svg);
  background-size: contain;
  box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
  background-repeat: no-repeat;
  background-position: center;
}
 
header {
  background-color: #2F8D46;
  text-align: center;
  padding: 10px 0;
  border-radius: 7px 7px 0 0;
}
 
header h2 {
  color: #fff;
  margin: 0;
}
 
.chatbox {
  padding: 15px;
  list-style: none;
  overflow-y: auto;
  height: 400px;
}
 
.chatbox li {
  margin-bottom: 10px;
}
 
.chat p {
  padding: 10px;
  border-radius: 10px;
  max-width: 70%;
  word-wrap: break-word;
}
 
.chat-outgoing p {
  background-color: #162887;
  align-self: flex-end;
  color: #fff;
}
 
.chat-incoming p {
  background-color: #eaeaea;
}
 
.chat-input {
  padding: 10px;
  border-top: 1px solid #ccc;
}
 
.chat-input textarea {
  width: 522px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 7px;
  resize: none;
  outline: none;
  overflow-y: scroll;
  background-color: #dcdcdc85;
  font-size: 16px;
  color: green;
  font-weight: 600;
  margin-top: -10px;
  margin-left: -15px;
  height: 71px;
}
 
#cross {
  float: right;
  position: relative;
  top: -38px;
  left: -15px;
  cursor: pointer;
  color: white;
  font-weight: bolder;
  font-size: 28px;
}
 
#cross:hover {
  color: red;
  transition: all .5s;
}
 
.chatbox .chat p.error {
  color: #ffffff;
  background-color: #ff3737e8;
}
 
#sendBTN {
  width: 100%;
  padding: 8px;
  border: 0;
  outline: none;
  font-size: 20px;
  font-weight: 600;
  border-radius: 7px;
  background-color: #2F8D46;
  cursor: pointer;
  color: white;
  margin-top: 12px;
}
 
.lastMessage {
  margin-top: 50px;
  font-size: 35px;
  font-weight: 600;
  color: darkgreen;
  margin-left: 550px;
}


Javascript




// script.js
 
const chatInput =
    document.querySelector('.chat-input textarea');
const sendChatBtn =
    document.querySelector('.chat-input button');
const chatbox = document.querySelector(".chatbox");
 
let userMessage;
const API_KEY =
    "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";
 
//OpenAI Free APIKey
 
const createChatLi = (message, className) => {
    const chatLi = document.createElement("li");
    chatLi.classList.add("chat", className);
    let chatContent =
        className === "chat-outgoing" ? `<p>${message}</p>` : `<p>${message}</p>`;
    chatLi.innerHTML = chatContent;
    return chatLi;
}
 
const generateResponse = (incomingChatLi) => {
    const messageElement = incomingChatLi
    .querySelector("p");
    const requestOptions = {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Authorization": `Bearer ${API_KEY}`
        },
        body: JSON.stringify({
            "model": "gpt-3.5-turbo",
            "messages": [
                {
                    role: "user",
                    content: userMessage
                }
            ]
        })
    };
 
    fetch(API_URL, requestOptions)
        .then(res => {
            if (!res.ok) {
                throw new Error("Network response was not ok");
            }
            return res.json();
        })
        .then(data => {
            messageElement
            .textContent = data.choices[0].message.content;
        })
        .catch((error) => {
            messageElement
            .classList.add("error");
            messageElement
            .textContent = "Oops! Something went wrong. Please try again!";
        })
        .finally(() => chatbox.scrollTo(0, chatbox.scrollHeight));
};
 
 
const handleChat = () => {
    userMessage = chatInput.value.trim();
    if (!userMessage) {
        return;
    }
    chatbox
    .appendChild(createChatLi(userMessage, "chat-outgoing"));
    chatbox
    .scrollTo(0, chatbox.scrollHeight);
 
    setTimeout(() => {
        const incomingChatLi = createChatLi("Thinking...", "chat-incoming")
        chatbox.appendChild(incomingChatLi);
        chatbox.scrollTo(0, chatbox.scrollHeight);
        generateResponse(incomingChatLi);
    }, 600);
}
 
sendChatBtn.addEventListener("click", handleChat);
 
function cancel() {
    let chatbotcomplete = document.querySelector(".chatBot");
    if (chatbotcomplete.style.display != 'none') {
        chatbotcomplete.style.display = "none";
        let lastMsg = document.createElement("p");
        lastMsg.textContent = 'Thanks for using our Chatbot!';
        lastMsg.classList.add('lastMessage');
        document.body.appendChild(lastMsg)
    }
}


Output: When API Key is working absolutely fine

ChatBot-GoogleChrome2024-03-0613-48-52-ezgifcom-crop

Chatbot Output

Note: When any error occurs any issue in the API Key

ChatBot-GoogleChrome2024-03-0613-49-49-ezgifcom-crop

Error in API



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads