Build Advanced AI Chatbot Using OpenAI, HTML, CSS, JavaScript

In our previous tutorial, we have explained about developing AI ChatBot using OpenAI and PHP. In this tutorial, we will explain to how to develop Advanced AI Chat using OpenAI, HTML, CSS, JavaScript.

AI Chatbots are very popular these days. These are computer program that uses artificial intelligence to simulate human conversation. These works with a combination of technologies such as NLP, machine learning, semantic search, etc., to understand user inputs and provide accurate responses.

In this tutorial, we will explain to develop dynamic AI ChatBot using OpenAI API with JavaScript, HTML and CSS.

So let’s proceed with developing AI Chatbot System. The file structure are:


  • advanced-ai-chatbot-openai-javascript
    • index.html
    • js
      • chatbot.js
    • css
      • style.css

1. Singup and Create OpenAI API Key

As we are going to use OpenAI, so we need to signup and create API Keys to use in our ChatBot. So after singup, go to https://platform.openai.com/api-keys and create API Keys and copy to use in application.

2. Design Responsive ChatBot Page

We will create index.html file and create HTML to design a responsive Chatbot page to send message and display responses as conversation.

<div class="main_container">
  <h1>AI Chatbot</h1>
  <p>Click on the chat icon to start a conversation with ChatBot</p>
</div>
<div class="container">
  <button class="chatbot-toggler">
	<span class="material-symbols-rounded">mode_comment</span>
	<span class="material-symbols-outlined">close</span>
  </button>
  <div class="chatbot">
	<header>
	  <h2>AI Chatbot</h2>
	  <span class="close-btn material-symbols-outlined">close</span>
	</header>
	<ul class="chatbox">
	  <li class="chat incoming">
		<span class="material-symbols-outlined"></span>
		<p>Hello 👏 <br />How can I assist you today?</p>
	  </li>		
	</ul>
	<div class="chat-input">
	  <textarea
		placeholder="Send a Message"
		spellcheck="false"
		required
	  ></textarea>
	  <span id="send-btn" class="material-symbols-outlined">send</span>
	</div>
  </div>
</div>

3. Implement AI ChatBot Functionality

We will create js/chatbot.js file and implement functionality for our Chatbot.

We will define a variable API_KEY and paste created OpenAI Secret key to access API.


const API_KEY = "API KEY"; 

We will create object of buttons, input, textarea to handle functionality.

const sendChatbtn = document.querySelector(".chat-input span");
const chatbotToggler = document.querySelector(".chatbot-toggler");
const closeBtn = document.querySelector(".close-btn");
const chatInput = document.querySelector(".chat-input textarea");
const chatbox = document.querySelector(".chatbox");

We will bind send button events and chat input events to handle functionality by calling functions handleConversation() to make request to API and get response to append in conversation.

chatInput.addEventListener("input", () => {  
  chatInput.style.height = `${inputInitHeight}px`;
  chatInput.style.height = `${chatInput.scrollHeight}px`;
});

chatInput.addEventListener("keydown", (e) => {  
  if (e.key === "Enter" && !e.shiftKey && window.innerWidth > 800) {
    e.preventDefault();
    handleConversation();
  }
});

sendChatbtn.addEventListener("click", handleConversation);

closeBtn.addEventListener("click", () =>
  document.body.classList.remove("show-chatbot")
);

chatbotToggler.addEventListener("click", () =>
  document.body.classList.toggle("show-chatbot")
);

We will define functions getResponse(), handleConversation(), createConversation() and implement functionality for our ChatBot.

let userMessage = null; 
const inputInitHeight = chatInput.scrollHeight;

const createConversation = (message, className) => {  
  const chatSection = document.createElement("li");
  chatSection.classList.add("chat", className);
  let chatContent =
    className === "outgoing"
      ? `<p></p>`
      : `<span class="material-symbols-outlined">smart_toy</span><p></p>`;
  chatSection.innerHTML = chatContent;
  chatSection.querySelector("p").textContent = message;
  return chatSection; 
};

const getResponse = (incomingChat) => {
	
  const API_URL = "https://api.openai.com/v1/chat/completions";
  const messageElement = incomingChat.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) => res.json())
    .then((data) => {
      messageElement.textContent = data.choices[0].message.content.trim();
    })
    .catch(() => {
      messageElement.classList.add("error");
      messageElement.textContent =
        "Oops Something went wrong. Please try again.";
    })
    .finally(() => chatbox.scrollTo(0, chatbox.scrollHeight));
};

const handleConversation = () => {
  userMessage = chatInput.value.trim(); 
  if (!userMessage) return;
  
  chatInput.value = "";
  chatInput.style.height = `${inputInitHeight}px`;
  
  const outgoingChatli = createConversation(userMessage, "outgoing");
  chatbox.appendChild(outgoingChatli);
  chatbox.scrollTo(0, chatbox.scrollHeight);

  setTimeout(() => {    
    const incomingChat = createConversation("Typing...", "incoming");
    chatbox.appendChild(incomingChat);
    getResponse(incomingChat);
  }, 600);
};


4. Style Page Design with CSS

Finally, we will create CSS for styling our Chatbot page.

@import url("https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,400;0,500;0,600;1,700&display=swap");

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}

.main_container {
  position: absolute;
  top: 50%;
  left: 40%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #fff;
  font-size: 2.5rem;
  font-weight: 600;
  letter-spacing: 0.5px;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.5);
  z-index: 1;
  @media (max-width: 991px) {
    font-size: 2rem;
  }
  @media (max-width: 767px) {
    font-size: 1.5rem;
  }
  @media (max-width: 575px) {
    font-size: 1.2rem;
  }
  @media (max-width: 375px) {
    font-size: 1rem;
  }
  @media (max-width: 320px) {
    font-size: 0.8rem;
  }
}

.container {
  height: 100vh;
  width: 100%;
  background: blue;
  background-size: 300%, 300%;
  animation: color 12s ease-in-out infinite;
}

@keyframes color {
  0% {
    background-position: 0 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0 50%;
  }
}

.chatbot-toggler {
  position: fixed;
  bottom: 40px;
  right: 40px;
  outline: none;
  border: none;
  height: 40px;
  width: 40px;
  display: flex;
  cursor: pointer;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: #4aa017;
  transition: all 0.2s ease;
  box-shadow: 0 0 128px 0 rgba(0, 0, 0, 0.1),
    0 32px 64px -48px rgba(0, 0, 0, 0.5);
  &:hover {
    background: #4aa017;
  }
  svg path {
    fill: #fff;
  }
  @media (max-width: 991px) {
    bottom: 20px;
    right: 20px;
  }
  @media (max-width: 767px) {
    bottom: 20px;
    right: 20px;
  }
  @media (max-width: 575px) {
    bottom: 20px;
    right: 20px;
  }
  @media (max-width: 375px) {
    bottom: 20px;
    right: 20px;
  }
  @media (max-width: 320px) {
    bottom: 20px;
    right: 20px;
  }
}
body.show-chatbot .chatbot-toggler {
  transform: rotate(90deg);
  background: #4aa017;
}
.chatbot-toggler span {
  color: #fff;
  position: absolute;
  font-size: 1.2rem;
  font-weight: 600;
  transition: all 0.2s ease;
}
.chatbot-toggler span:last-child,
body.show-chatbot .chatbot-toggler span:first-child {
  opacity: 0;
}
body.show-chatbot .chatbot-toggler span:last-child {
  opacity: 1;
}

.chatbot {
  position: fixed;
  right: 70px;
  bottom: 80px;
  overflow: hidden;
  width: 340px;
  height: 520px;
  transform: scale(0.5);
  opacity: 0;
  pointer-events: none;
  background: #fff;
  transform-origin: bottom right;
  border-radius: 15px;
  box-shadow: 0 0 128px 0 rgba(0, 0, 0, 0.1),
    0 32px 64px -48px rgba (0, 0, 0, 0.5);
  transition: all 0.1s ease;
}

body.show-chatbot .chatbot {
  opacity: 1;
  pointer-events: auto;
  transform: scale(1);
}

/* ChatBot */
.chatbot header {
  background: #4aa017;
  position: relative;
  color: #fff;
  padding: 15px 0;
  text-align: center;
  border-radius: 15px 15px 0 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.chatbot header span {
  position: absolute;
  right: 15px;
  top: 50%;
  display: none;
  cursor: pointer;
  transform: translateY(-50%);
}
@media screen and (max-width: 992px) {
  .chatbot header span {
    display: block;
  }
}
.chatbot header span svg {
  height: 20px;
  width: 20px;
  fill: #fff;
}
.chatbot header span:hover {
  opacity: 0.8;
}
.chatbot header span:first-child {
  right: 55px;
}
.chatbot header span:last-child {
  right: 15px;
}

.chatbot header h2 {
  color: #fff;
  font-size: 1.4rem;
  font-weight: 600;
  letter-spacing: 0.5px;
}
.chatbot .chatbox {
  overflow-y: auto;
  padding: 15px 10px 8px;
  height: 400px;
  background: #fff;
  border-radius: 0 0 15px 15px;
  box-shadow: 0 0 2px rgba(0, 0, 0, 0.1);
}
.chatbox .chat {
  display: flex;
  list-style: none;
  margin: -1px 0 0;
}
.chatbot :where(.chatbox, textarea)::-webkit-scrollbar {
  width: 6px;
}
.chatbot :where(.chatbox, textarea)::-webkit-scrollbar-track {
  background: #fff;
  border-radius: 25px;
}
.chatbot :where(.chatbox, textarea)::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 25px;
}
.chatbot :where(.chatbox, textarea)::-webkit-scrollbar-thumb:hover {
  background: #b3b3b3;
}

.chatbox .incoming span {
  height: 30px;
  width: 30px;
  color: #fff;
  align-self: flex-end;
  background: #4aa017;
  text-align: center;
  line-height: 32px;
  border-radius: 5px;
  margin: 0 8px 2px 0;
}

.chatbox .outgoing {
  margin: 20px 0;
  justify-content: flex-end;
  font-size: 0.8rem;
}
.chatbox .chat p {
  color: #fff;
  font-size: 0.9rem;
  max-width: 75%;
  padding: 5px 10px;
  border-radius: 10px 10px 0 10px;
  background: #4aa017;
  line-height: 1.3;
  box-shadow: 0 0 2px rgba(0, 0, 0, 0.1);
}

.chatbox .incoming p {
  color: black;
  font-size: 0.9rem;
  background: #f2f2f2;
  border-radius: 10px 10px 10px 0;
  text-align: left;
  box-shadow: 0 0 2px rgba(0, 0, 0, 0.1);
}

.chatbox .chat p.error {
  color: #721c24;
  background: #f8d7da;
}

.chatbox .chat p.error::before {
  content: "!";
  color: #721c24;
  font-weight: 600;
  margin-right: 5px;
}

.chatbox .chat p.error::after {
  content: "!";
  color: #721c24;
  font-weight: 600;
  margin-left: 5px;
}

.chatbox .chat p.error {
  color: #721c24;
  background: #f8d7da;
}
@media (max-width: 375px) and (-webkit-min-device-pixel-ratio: 2),
  (max-width: 375px) and (min-device-pixel-ratio: 2) {
  .chatbox .chat p.error {
    background: #f8d7da;
    color: #721c24;
  }
}

.chatbot .chat-input {
  position: absolute;
  bottom: 0;
  width: 100%;
  display: flex;
  gap: 5px;
  background: #fff;
  padding: 5px 20px;
  border-top: 1px solid #ccc;
}

.chat-input textarea {
  height: 55px;
  width: 100%;
  border: none;
  outline: none;
  font-size: 0.95rem;
  resize: none;
  padding: 16px 15px 16px 0;
  border-radius: 5px;
  box-shadow: 0 0 2px rgba(0, 0, 0, 0.1);
}

.chat-input span {
  align-self: flex-end;
  height: 40px;
  line-height: 55px;
  color: #4aa017;
  font-size: 1.35rem;
  cursor: pointer;
  visibility: hidden;
  transition: 0.3s ease;
  justify-content: flex-end;
}

.chat-input textarea:valid ~ span {
  visibility: visible;
}
@media (max-width: 767px) {
  .chatbot {
    width: 100%;
    height: 100%;
    border-radius: 0;
    bottom: 0;
    right: 0;
  }
  .chatbot header {
    border-radius: 0;
  }
  .chatbot .chat-input {
    position: relative;
  }
  .chatbot .chat-input textarea {
    padding: 16px 15px 16px 0;
  }
  .chatbot .chat-input span {
    height: 55px;
    line-height: 55px;
    font-size: 1.35rem;
  }
}

@media (max-width: 575px) {
  .chatbot {
    width: 100%;
    height: 100%;
    border-radius: 0;
    bottom: 0;
    right: 0;
  }
  .chatbot header {
    border-radius: 0;
  }
  .chatbot .chat-input {
    position: relative;
  }
  .chatbot .chat-input textarea {
    padding: 16px 15px 16px 0;
  }
  .chatbot .chat-input span {
    height: 55px;
    line-height: 55px;
    font-size: 1.35rem;
  }
}

You can view the live demo from the Demo link and can download the full script from the Download link below.
Demo Download


Leave a Reply

Your email address will not be published. Required fields are marked *