Chatbot with Gemini API Using HTML, CSS & JavaScrip
Chatbot with Gemini API Using HTML, CSS & JavaScrip

Build Your Own AI Chatbot Using Gemini API (Step-by-Step Guide with Code)

Chatbots are everywhere today – from customer service to personal assistants. In this tutorial, we’ll build a floating chatbot widget for your website using HTML, CSS, JavaScript, and connect it to Google’s Gemini API for smart AI-powered responses.

By the end, you’ll have a modern chatbot that looks great and works in real time.

Features of Our Chatbot

  • 💬 Floating chat icon that expands into a chatbot window
  • ⚡ Real-time AI-powered conversations using Gemini API
  • 🎨 Stylish design with animations and gradients
  • 📱 Fully responsive and mobile-friendly

🛠 Step 1: Project Setup

Create a project folder called chatbot-project. Inside it, create three files:

chatbot-project/
│── index.html
│── style.css
│── script.js

Step 2: HTML Structure (index.html)

This is the base layout of our chatbot widget and landing page.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>ChatBot Project</title>
  <link rel="stylesheet" href="./style.css" />
</head>

<body>
  <!-- Landing Page Content -->
  <header class="hero">
    <h1>💬 Welcome to My ChatBot Project</h1>
    <p>Your personal assistant powered by AI – click the chat icon below to start chatting!</p>
  </header>

  <section class="info-section">
    <div class="info-card">
      <h2>⚡ Real-Time Conversations</h2>
      <p>Ask anything and get instant responses.</p>
    </div>
    <div class="info-card">
      <h2>🤖 AI-Powered</h2>
      <p>Powered by Gemini API for smart answers.</p>
    </div>
    <div class="info-card">
      <h2>🌐 Available 24/7</h2>
      <p>Always online, ready to assist you.</p>
    </div>
  </section>

  <!-- Floating Chat Icon -->
  <div id="chatbot-icon" title="Chat with us">💬</div>

  <!-- Chatbot Window -->
  <div id="chatbot-container" class="hidden">
    <div id="chatbot-header">
      <span>💡 ChatBot Assistant</span>
      <button id="close-btn">&times;</button>
    </div>

    <div id="chatbot-body">
      <div id="chatbot-messages"></div>
      <div id="typing-indicator" class="hidden">Bot is typing...</div>
    </div>

    <div id="chatbot-input-container">
      <input type="text" id="chatbot-input" placeholder="Type a message..." />
      <button id="send-btn">➤</button>
    </div>
  </div>

  <script src="./script.js"></script>
</body>

</html>

✅ This file creates:

  • A landing page with intro text and feature cards
  • A floating chat icon (💬)
  • A chat window with messages, typing indicator, and input box

Step 3: Styling (style.css)

Now let’s make it beautiful with CSS.

/* Background + Page Styling */
body {
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
  background: linear-gradient(135deg, #141e30, #243b55);
  margin: 0;
  padding: 0;
  color: #fff;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

/* Hero Section */
.hero {
  margin-top: 80px;
}

.hero h1 {
  font-size: 2.5rem;
  margin-bottom: 15px;
  color: #4facfe;
}

.hero p {
  font-size: 1.2rem;
  color: #ddd;
  max-width: 600px;
  margin: auto;
}

/* Info Section */
.info-section {
  display: flex;
  gap: 20px;
  margin: 50px 20px;
  flex-wrap: wrap;
  justify-content: center;
}

.info-card {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 15px;
  padding: 20px;
  width: 250px;
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.3);
  transition: transform 0.2s ease;
}

.info-card:hover {
  transform: scale(1.05);
}

.info-card h2 {
  color: #00f2fe;
  margin-bottom: 10px;
}

.info-card p {
  color: #ccc;
}

/* Floating Chat Icon */
#chatbot-icon {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 65px;
  height: 65px;
  background: linear-gradient(135deg, #4facfe, #00f2fe);
  color: white;
  font-size: 28px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.5);
  cursor: pointer;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  z-index: 1000;
}

#chatbot-icon:hover {
  transform: scale(1.15);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.6);
}

/* Chatbot Container */
#chatbot-container {
  position: fixed;
  bottom: 85px;
  right: 20px;
  width: 370px;
  height: 480px;
  background: rgba(30, 30, 30, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  box-shadow: 0 12px 35px rgba(0, 0, 0, 0.6);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  animation: slideUp 0.3s ease;
  z-index: 2000;
}

/* Slide Up Animation */
@keyframes slideUp {
  from {
    transform: translateY(40px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

/* Hide Chatbot Initially */
.hidden {
  display: none !important;
}

/* Chatbot Header */
#chatbot-header {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
  color: white;
  padding: 14px 18px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

#close-btn {
  background: none;
  border: none;
  color: white;
  font-size: 22px;
  cursor: pointer;
}

/* Chatbot Body */
#chatbot-body {
  flex: 1;
  padding: 12px;
  overflow-y: auto;
}

/* Chatbot Messages */
#chatbot-messages {
  display: flex;
  flex-direction: column;
}

.message {
  margin-bottom: 12px;
  padding: 12px 15px;
  border-radius: 16px;
  max-width: 80%;
  font-size: 15px;
  line-height: 1.4;
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.3);
  animation: popIn 0.2s ease;
}

@keyframes popIn {
  from { transform: scale(0.9); opacity: 0.5; }
  to { transform: scale(1); opacity: 1; }
}

.message.user {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
  color: white;
  align-self: flex-end;
}

.message.bot {
  background: #2f3640;
  color: #e0e0e0;
  align-self: flex-start;
}

/* Typing Indicator */
#typing-indicator {
  font-size: 14px;
  color: #bbb;
  margin: 5px 0;
  padding-left: 5px;
  font-style: italic;
}

/* Input Section */
#chatbot-input-container {
  display: flex;
  padding: 12px;
  border-top: 1px solid #444;
  background: rgba(40, 40, 40, 0.95);
}

#chatbot-input {
  flex: 1;
  padding: 12px;
  border: 1px solid #555;
  border-radius: 12px;
  background-color: #1e1e1e;
  color: white;
  outline: none;
  transition: border 0.2s;
}

#chatbot-input:focus {
  border-color: #4facfe;
}

#send-btn {
  margin-left: 10px;
  padding: 10px 16px;
  background: linear-gradient(135deg, #4facfe, #00f2fe);
  color: white;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  font-size: 15px;
  transition: transform 0.2s, background 0.2s;
}

#send-btn:hover {
  transform: scale(1.05);
  background: linear-gradient(135deg, #00f2fe, #4facfe);
}

✅ Now the chatbot looks professional with smooth animations and gradients.

Step 4: JavaScript Logic (script.js)

This file handles open/close, sending messages, and Gemini API calls.

document.addEventListener("DOMContentLoaded", function () {
  const chatbotContainer = document.getElementById("chatbot-container");
  const closeBtn = document.getElementById("close-btn");
  const sendBtn = document.getElementById("send-btn");
  const chatBotInput = document.getElementById("chatbot-input");
  const chatbotMessages = document.getElementById("chatbot-messages");
  const chatbotIcon = document.getElementById("chatbot-icon");

  chatbotIcon.addEventListener("click", () => {
    chatbotContainer.classList.remove("hidden");
    chatbotIcon.style.display = "none";
  });
  closeBtn.addEventListener("click", () => {
    chatbotContainer.classList.add("hidden");
    chatbotIcon.style.display = "flex";
  });

  sendBtn.addEventListener("click", sendMessage);

  chatBotInput.addEventListener("keypress", (e) => {
    if (e.key === "Enter") sendMessage();
  });
});

function sendMessage() {
  const userMessage = document.getElementById("chatbot-input").value.trim();
  if (userMessage) {
    appendMessage("user", userMessage);
    document.getElementById("chatbot-input").value = "";
    getBotResponse(userMessage);
  }
}

function appendMessage(sender, message) {
  const messageContainer = document.getElementById("chatbot-messages");
  const messageElement = document.createElement("div");
  messageElement.classList.add("message", sender);

  // Format response text
  const formattedMessage = message
    .replace(/\n{2,}/g, "<br><br>")
    .replace(/\n/g, "<br>")
    .trim();

  messageElement.innerHTML = formattedMessage;
  messageContainer.appendChild(messageElement);
  messageContainer.scrollTop = messageContainer.scrollHeight;
}

async function getBotResponse(userMessage) {
  const API_KEY = "YOUR_GEMINI_API_KEY"; // Replace with your actual API Key

  const API_URL = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${API_KEY}`;

  try {
    const response = await fetch(API_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        contents: [
          {
            parts: [{ text: userMessage }],
          },
        ],
      }),
    });

    const data = await response.json();

    if (!data.candidates || !data.candidates.length) {
      throw new Error("No response from Gemini API");
    }

    const botMessage = data.candidates[0].content.parts[0].text;
    appendMessage("bot", botMessage);
  } catch (error) {
    console.error("Error:", error);
    appendMessage(
      "bot",
      "⚠️ Sorry, I'm having trouble responding. Please try again."
    );
  }
}

✅ Here’s what this does:

  • Opens/closes chatbot when clicking the 💬 icon
  • Sends user input to Gemini API
  • Displays AI’s response in chat window

Step 5: Get Gemini API Key

  1. Go to Google AI Studio
  2. Create a project and enable Gemini API
  3. Generate an API Key
  4. Replace YOUR_GEMINI_API_KEY in script.js

Final Output

AI-powered responses from Gemini API

A landing page with feature cards

A floating chat icon in the corner

A chat window that opens when clicked

When you run the project in your browser, you’ll see:

git code is available at https://github.com/110059/chatbot

Similar Posts