Create a Simple Chatbot Using JavaScript

Create a Simple Chatbot Using JavaScript

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

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!

Related Posts

Leave a Reply

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