Skip to content
Youths Forum Youths Forum Youths Forum

Tech Blogs & Programming Tutorials

Youths Forum Youths Forum Youths Forum

Tech Blogs & Programming Tutorials

  • Blog
  • News
  • Programming
    • PHP
    • JavaScript
    • JQuery
    • CSS
    • HTML
    • API
  • Stock Market Live
  • Automobiles
    • Cars
  • Gadgets
    • Phones
    • Android Phones

Categories

  • Automobiles (12)
    • Cars (7)
  • Blog (103)
    • Poems (2)
    • Space (2)
  • Command (2)
  • Education (2)
  • Entertainment (4)
  • Gadgets (9)
    • Phones (8)
      • Android Phones (4)
  • HTML Templates (11)
  • IT Training Institutes (1)
  • Lifestyle (4)
  • News (51)
  • Others (23)
  • Programming (296)
    • API (16)
    • CSS (83)
    • Database (4)
    • Hosting (1)
    • HTML (37)
    • JavaScript (117)
      • JQuery (27)
      • ReactJS (7)
    • PHP (116)
  • Python (3)
  • recipes (1)
  • SEE Result (1)
  • Server (3)
  • Blog
  • News
  • Programming
    • PHP
    • JavaScript
    • JQuery
    • CSS
    • HTML
    • API
  • Stock Market Live
  • Automobiles
    • Cars
  • Gadgets
    • Phones
    • Android Phones
Close

Search

JavaScriptProgramming

Create a Simple Chatbot Using JavaScript

By Admin
October 20, 2024 3 Min Read
0

Building a chatbot may seem complex, but you can create a simple one using only HTML, CSS, and JavaScript. In this article, we’ll guide you through the process of developing a basic chatbot with predefined responses, walking you through each part of the code.

Follow this video for complete guidance

https://www.youtube.com/watch?v=P4LeN2MtDXo

Step 1: Structure with HTML

We start by setting up the basic structure of the chatbot in HTML. This includes a container for chat messages and an input box for users to send their messages.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Chatbot</title>
</head>
<body>
    <div class="chat-container">
        <div class="chat-messages" id="chat-messages"></div>
        <div class="chat-input">
            <input type="text" id="user-input" placeholder="Type your message...">
            <button id="send-button">Send</button>
        </div>
    </div>
</body>
</html>

Here, the chatbot interface consists of two main sections:

  • Message Display Area: A div (chat-messages) to show the chat conversation.
  • Input Area: A text input and button for users to send messages.

Step 2: Styling with CSS

Next, we add styles to make the chatbot visually appealing. The CSS will help us create a simple but clean look.

<style>
    body {
        font-family: Arial, sans-serif;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
        margin: 0;
        background-color: #f0f0f0;
    }
    .chat-container {
        width: 300px;
        border: 1px solid #ccc;
        border-radius: 5px;
        overflow: hidden;
    }
    .chat-messages {
        height: 300px;
        overflow-y: auto;
        padding: 10px;
        background-color: #fff;
    }
    .user-message {
        background-color: #e1ffc7;
        padding: 5px 10px;
        border-radius: 10px;
        margin-bottom: 10px;
        max-width: 80%;
        align-self: flex-end;
    }
    .bot-message {
        background-color: #f0f0f0;
        padding: 5px 10px;
        border-radius: 10px;
        margin-bottom: 10px;
        max-width: 80%;
        align-self: flex-start;
    }
    .chat-input {
        display: flex;
        padding: 10px;
        background-color: #f9f9f9;
    }
    #user-input {
        flex-grow: 1;
        border: 1px solid #ccc;
        border-radius: 3px;
        padding: 5px;
    }
    #send-button {
        border: none;
        background-color: #4CAF50;
        color: white;
        padding: 5px 10px;
        margin-left: 5px;
        border-radius: 3px;
        cursor: pointer;
    }
</style>

This CSS ensures:

  • A centered layout for the chatbot.
  • Differentiated message bubbles for the user and the bot.
  • A scrollable message display area to keep the interface neat.

Step 3: Adding Functionality with JavaScript

Now, let’s bring the chatbot to life using JavaScript. We’ll use predefined responses based on simple keywords. The script adds user messages to the chat and provides corresponding bot responses.

<script>
    const chatMessages = document.getElementById('chat-messages');
    const userInput = document.getElementById('user-input');
    const sendButton = document.getElementById('send-button');

    const botResponses = {
        "hello": "Hi there! How can I help you today?",
        "how are you": "I'm doing well, thank you for asking!",
        "what's your name": "My name is ChatBot. It's nice to meet you!",
        "bye": "Goodbye! Have a great day!",
        "default": "I'm not sure how to respond to that. Can you try asking something else?"
    };

    function addMessage(message, isUser) {
        const messageElement = document.createElement('div');
        messageElement.classList.add(isUser ? 'user-message' : 'bot-message');
        messageElement.textContent = message;
        chatMessages.appendChild(messageElement);
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    function getBotResponse(userMessage) {
        const lowercaseMessage = userMessage.toLowerCase();
        return botResponses[lowercaseMessage] || botResponses["default"];
    }

    function handleUserInput() {
        const message = userInput.value.trim();
        if (message) {
            addMessage(message, true);
            userInput.value = '';

            setTimeout(() => {
                const botResponse = getBotResponse(message);
                addMessage(botResponse, false);
            }, 500);
        }
    }

    sendButton.addEventListener('click', handleUserInput);
    userInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            handleUserInput();
        }
    });

    // Initial bot greeting
    addMessage("Hello! I'm a simple chatbot. How can I help you today?", false);
</script>

Breakdown of the JavaScript Code:

  • Message Handling: The addMessage() function displays user or bot messages in the chat window. It appends the message as a div and scrolls to the bottom automatically.
  • Bot Responses: The getBotResponse() function checks the user’s message and returns a corresponding bot reply from the predefined list. If no match is found, the bot gives a default response.
  • User Input: The handleUserInput() function captures the user’s input, displays it, and triggers the bot response after a slight delay (to simulate real interaction).
  • Initial Greeting: The bot greets the user with a welcome message when the page loads.

This simple chatbot is an excellent starting point to understand the basic interaction between a user and a bot. You can expand its functionality by integrating natural language processing (NLP) services like Dialogflow or creating more sophisticated responses. By following this guide, you’ve built your first chatbot using HTML, CSS, and JavaScript!

Author

Admin

Follow Me
Other Articles
Previous

Build a Photo Booth App using HTML, CSS, and JavaScript

Next

Eye-catching Delete Button designs

No Comment! Be the first one.

Leave a Reply

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

FIFA World Cup 2026 Predict and Win by SportsGuff

Recent Posts

  • Unpacking Nepal’s Record Rs 2.12 Trillion Budget and What It Means for You
  • How to Write a Strong Scholarship Application: The Ultimate Step-by-Step Guide
  • How to Prepare for Exams Without Stress: The Ultimate Science-Backed Guide
  • Chiranjibi Adhikari Appointed Acting President of CAN Federation
  • How to Design a Student Marksheet Using HTML and CSS

Tags

adsense ai animate animation animation using HTML and CSS API blog calculator chatgpt Cryptocurrency CSS css animation design Email Facebook featured filemanager file manager free template google htaccess HTML image Instagram interview javascript JQuery jquery ui NADA AutoShow NADA Auto Show 2024 password PHP Progressive Web App PWA QR random react reactjs Rotate travel Twitter vpn youthforum youthsforum youtube

About Us

At Youths Forum, we are passionate about sharing knowledge that empowers students, educators, professionals, and technology enthusiasts.

Our Mission

Our mission is simple: to make technology and education accessible, understandable, and beneficial for everyone. We strive to create content that helps our readers learn new skills and stay updated with industry developments.

RSS RSS

  • Unpacking Nepal’s Record Rs 2.12 Trillion Budget and What It Means for You Admin
  • How to Write a Strong Scholarship Application: The Ultimate Step-by-Step Guide Admin
  • How to Prepare for Exams Without Stress: The Ultimate Science-Backed Guide Admin

Quick Links

  • Stock Market Live
  • Parliament Election 2082
Copyright 2026 — Youths Forum. All rights reserved. Blogsy WordPress Theme