Just Jolly Functions
Functions: Adding a Chatbot with HTML, CSS, and JavaScript
This article provides a comprehensive approach to customizing a chatbot built using HTML, CSS, and JavaScript. It outlines various strategies to modify the chatbot’s appearance, behavior, and interactivity, empowering you to tailor it according to your needs.
Tips:
Learn how to Insert HTML Code into Your Post.
You can also develop a chatbot using a Chatbot Builder.
Here is the full code for a Simple Chatbot:
<!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>
<style>
/* General Reset */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* Body */
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
/* Chat Container */
.chat-container {
background-color: #fff;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
width: 400px;
max-width: 100%;
height: 500px;
display: flex;
flex-direction: column;
justify-content: space-between;
overflow: hidden;
}
/* Chat Box */
.chat-box {
padding: 15px;
flex-grow: 1;
overflow-y: auto;
height: 90%;
background-color: #e4e4e4;
border-bottom: 2px solid #ddd;
}
/* Chat Messages */
.chat-message {
background-color: #f1f1f1;
padding: 10px;
border-radius: 10px;
margin-bottom: 10px;
max-width: 70%;
line-height: 1.5;
}
.bot-message {
background-color: #d1e7dd;
align-self: flex-start;
}
.user-message {
background-color: #cfe2f3;
align-self: flex-end;
}
/* User Input Container */
.user-input-container {
display: flex;
padding: 10px;
background-color: #fff;
border-top: 1px solid #ddd;
}
#user-input {
flex-grow: 1;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
margin-right: 10px;
font-size: 16px;
}
button {
padding: 10px 15px;
background-color: #007bff;
border: none;
color: white;
font-size: 16px;
cursor: pointer;
border-radius: 5px;
}
button:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<div class="chat-container">
<div class="chat-box" id="chat-box">
<div class="chat-message bot-message">Hello! How can I help you today?</div>
</div>
<div class="user-input-container">
<input type="text" id="user-input" placeholder="Type a message..." />
<button onclick="sendMessage()">Send</button>
</div>
</div>
<script>
// Function to handle sending messages
function sendMessage() {
const userInput = document.getElementById('user-input');
const userMessage = userInput.value.trim();
if (userMessage) {
// Append user message to the chat
addMessage(userMessage, 'user-message');
// Clear the input field
userInput.value = '';
// Simulate a response from the bot after a brief delay
setTimeout(() => {
const botResponse = getBotResponse(userMessage);
addMessage(botResponse, 'bot-message');
}, 1000);
}
}
// Function to add a message to the chat
function addMessage(message, sender) {
const chatBox = document.getElementById('chat-box');
const messageElement = document.createElement('div');
messageElement.classList.add('chat-message', sender);
messageElement.textContent = message;
chatBox.appendChild(messageElement);
chatBox.scrollTop = chatBox.scrollHeight; // Scroll to bottom to show the latest message
}
// Function to simulate a bot response
function getBotResponse(userMessage) {
const lowerMessage = userMessage.toLowerCase();
if (lowerMessage.includes('hello') || lowerMessage.includes('hi')) {
return 'Hello! How can I assist you today?';
} else if (lowerMessage.includes('how are you')) {
return 'I am just a bot, but I am functioning well! How about you?';
} else if (lowerMessage.includes('bye')) {
return 'Goodbye! Have a great day!';
} else {
return 'I am sorry, I did not understand that. Can you rephrase?';
}
}
</script>
</body>
</html>
Explanation of the Code:
HTML:
The HTML structure consists of a main chat-container that houses a chat-box where the chat messages are displayed.
A user-input-container holds the text input field and a send button that allows users to submit their messages.
CSS:
Basic styling is applied to elements like the chat-container, chat-box, and the chat message bubbles (bot and user).
Flexbox is used for alignment and layout, especially for positioning the user input section at the bottom of the page.
Buttons and input fields have hover effects to make the UI interactive.
JavaScript:
sendMessage(): This function is triggered when the user clicks the "Send" button. It collects the input message, adds it to the chat, and simulates a bot response after a short delay.
addMessage(): This function creates a new div element for each message (either user or bot) and appends it to the chat-box. It also ensures that the chat scrolls to the bottom so that the latest message is always visible.
getBotResponse(): This function checks the user message for certain keywords and returns an appropriate response. It handles simple conversational interactions like greetings ("hello", "hi") and basic responses for phrases like "how are you" and "bye". If the bot doesn't understand, it asks the user to rephrase.
This code is a simple, functional chatbot with no advanced features like natural language processing, but it works well for basic interaction.
1. HTML Structure:
The HTML structure defines the elements for the chatbot interface, which includes a chat box to display the conversation and an input field for the user to type 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>
<style>
/* CSS styles go here */
</style>
</head>
<body>
<div class="chat-container">
<div class="chat-box" id="chat-box">
<div class="chat-message bot-message">Hello! How can I help you today?</div>
</div>
<div class="user-input-container">
<input type="text" id="user-input" placeholder="Type a message..." />
<button onclick="sendMessage()">Send</button>
</div>
</div>
<script>
// JavaScript goes here
</script>
</body>
</html>
<html lang="en">: Defines the language of the page as English.
<meta charset="UTF-8">: Specifies the character encoding for the document as UTF-8.
<meta name="viewport" content="width=device-width, initial-scale=1.0">: Ensures the page is responsive on mobile devices by setting the viewport properties.
<title>: Sets the title of the page that appears in the browser tab.
<style>: Contains the CSS that styles the chatbot interface.
<script>: Contains the JavaScript that powers the chatbot's functionality.
2. CSS Styling:
The CSS section defines how the chatbot and its components (like chat messages, input field, and button) will appear on the page. Here's a breakdown of the key styles:
/* General Reset */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
General Reset: Resets the default margin, padding, and box-sizing properties of all elements to create a consistent base style.
/* Body */
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
Body Styling: Uses flexbox to center the chatbot vertically and horizontally within the page. It also sets a light background color and removes the default margin.
/* Chat Container */
.chat-container {
background-color: #fff;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
width: 400px;
max-width: 100%;
height: 500px;
display: flex;
flex-direction: column;
justify-content: space-between;
overflow: hidden;
}
Chat Container: This section is the main container for the chatbot. It has a white background, rounded corners (border-radius), a subtle shadow (box-shadow), and a fixed height. It uses flexbox to organize the layout.
/* Chat Box */
.chat-box {
padding: 15px;
flex-grow: 1;
overflow-y: auto;
height: 90%;
background-color: #e4e4e4;
border-bottom: 2px solid #ddd;
}
Chat Box: This is the area where the chat messages will appear. It has padding for spacing, a light gray background, and a scrollbar (overflow-y: auto) when the content overflows.
/* Chat Messages */
.chat-message {
background-color: #f1f1f1;
padding: 10px;
border-radius: 10px;
margin-bottom: 10px;
max-width: 70%;
line-height: 1.5;
}
Chat Messages: Each message (from both the bot and the user) is styled with a light gray background, padding, rounded corners, and margin between messages. The max-width: 70% limits the width of each message.
/* Bot and User Messages */
.bot-message {
background-color: #d1e7dd;
align-self: flex-start;
}
.user-message {
background-color: #cfe2f3;
align-self: flex-end;
}
Bot and User Message Styles: The bot's messages are given a distinct background color and aligned to the left (align-self: flex-start), while the user's messages are aligned to the right (align-self: flex-end) and have a different background color.
/* User Input Container */
.user-input-container {
display: flex;
padding: 10px;
background-color: #fff;
border-top: 1px solid #ddd;
}
User Input Container: The container for the input field and the send button, which is placed at the bottom of the chat. It uses flexbox to position the elements.
#user-input {
flex-grow: 1;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
margin-right: 10px;
font-size: 16px;
}
Input Field: The text input field for the user to type their message. It is styled with padding, a border, and a rounded corner.
button {
padding: 10px 15px;
background-color: #007bff;
border: none;
color: white;
font-size: 16px;
cursor: pointer;
border-radius: 5px;
}
button:hover {
background-color: #0056b3;
}
Send Button: The send button has a blue background color, white text, and rounded corners. The hover effect changes its background color when the user hovers over it.
3. JavaScript Functionality:
The JavaScript code is responsible for sending and receiving messages, as well as handling the logic behind the chatbot's responses.
// Function to handle sending messages
function sendMessage() {
const userInput = document.getElementById('user-input');
const userMessage = userInput.value.trim();
if (userMessage) {
// Append user message to the chat
addMessage(userMessage, 'user-message');
// Clear the input field
userInput.value = '';
// Simulate a response from the bot after a brief delay
setTimeout(() => {
const botResponse = getBotResponse(userMessage);
addMessage(botResponse, 'bot-message');
}, 1000);
}
}
sendMessage(): This function is triggered when the user clicks the "Send" button. It gets the message from the input field, appends it to the chat, clears the input field, and then waits for 1 second (setTimeout) before generating a bot response.
// Function to add a message to the chat
function addMessage(message, sender) {
const chatBox = document.getElementById('chat-box');
const messageElement = document.createElement('div');
messageElement.classList.add('chat-message', sender);
messageElement.textContent = message;
chatBox.appendChild(messageElement);
chatBox.scrollTop = chatBox.scrollHeight; // Scroll to bottom to show the latest message
}
addMessage(): This function creates a new div element with the appropriate class (user-message or bot-message) and appends it to the chat box. It also ensures the chat scrolls to the bottom to show the latest message.
// Function to simulate a bot response
function getBotResponse(userMessage) {
const lowerMessage = userMessage.toLowerCase();
if (lowerMessage.includes('hello') || lowerMessage.includes('hi')) {
return 'Hello! How can I assist you today?';
} else if (lowerMessage.includes('how are you')) {
return 'I am just a bot, but I am functioning well! How about you?';
} else if (lowerMessage.includes('bye')) {
return 'Goodbye! Have a great day!';
} else {
return 'I am sorry, I did not understand that. Can you rephrase?';
}
}
getBotResponse(): This function determines the chatbot's response based on the user's input. It checks if the message contains certain keywords like "hello", "how are you", or "bye" and responds accordingly. If the message doesn't match any of these, it returns a generic response asking the user to rephrase.
Chatbot Modifications:
Customizing a chatbot involves tweaking various aspects such as appearance, behavior, and functionality. Below are detailed steps on how to customize your chatbot using the code provided earlier. You can modify different parts of the HTML, CSS, and JavaScript to make the chatbot fit your needs.
1. Customizing the Appearance (CSS)
The design of your chatbot can be customized using CSS. You can adjust colors, fonts, sizes, and layouts to match your style. Here are some customizations you can make:
a. Change the Chatbox Dimensions and Layout
Modify the size of the chat container and chat box to fit your desired layout:
.chat-container {
width: 500px; /* Increase width */
height: 600px; /* Increase height */
}
b. Customize Background and Bubble Colors
You can change the background colors of the chat container and the message bubbles. For example:
/* Bot message bubble */
.bot-message {
background-color: #d0f0c0; /* Light green */
color: #2e2e2e;
}
/* User message bubble */
.user-message {
background-color: #cce7ff; /* Light blue */
color: #2e2e2e;
}
/* Chat container background */
.chat-container {
background-color: #fff; /* White background */
}
c. Modify Button Appearance
Change the button appearance (like the color and hover effects):
button {
background-color: #28a745; /* Green background */
color: white;
}
button:hover {
background-color: #218838; /* Darker green */
}
d. Font Customization
To make your chatbot more attractive, you can change the fonts:
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
2. Customizing Chatbot Behavior (JavaScript)
To adjust how the chatbot responds or to add additional interactions, modify the JavaScript code.
a. Change the Bot’s Responses
The getBotResponse() function controls how the bot replies to user inputs. You can add more complex logic or modify existing ones. For example, if you want to add a personalized response for a different greeting, you can do so like this:
function getBotResponse(userMessage) {
const lowerMessage = userMessage.toLowerCase();
if (lowerMessage.includes('hello') || lowerMessage.includes('hi')) {
return 'Hello! How can I help you today?';
} else if (lowerMessage.includes('how are you')) {
return 'I’m doing well! How can I assist you today?';
} else if (lowerMessage.includes('what is your name')) {
return 'I’m a friendly chatbot! What can I do for you?';
} else if (lowerMessage.includes('bye')) {
return 'Goodbye! Take care and have a great day!';
} else {
return 'Sorry, I didn’t understand that. Could you please clarify?';
}
}
b. Add More Interactive Features
You can create custom responses to certain queries. For instance, if a user types "weather," the chatbot can reply with a weather-related response. You could even integrate real-time data by fetching it via an API, though that requires more advanced coding. Here's an example of a weather feature:
function getBotResponse(userMessage) {
const lowerMessage = userMessage.toLowerCase();
if (lowerMessage.includes('weather')) {
return 'I am unable to check the weather right now, but you can check your favorite weather app!';
}
// Add more custom responses as needed
}
c. Add Delayed Responses
If you'd like to simulate a more human-like response time, you can adjust the setTimeout delay when sending bot messages:
setTimeout(() => {
const botResponse = getBotResponse(userMessage);
addMessage(botResponse, 'bot-message');
}, 2000); // Delay response by 2 seconds
3. Adding Custom Commands
You can extend the chatbot to handle specific commands. For example, if the user types "help," the bot can display a list of commands it understands:
function getBotResponse(userMessage) {
const lowerMessage = userMessage.toLowerCase();
if (lowerMessage.includes('help')) {
return 'I can help you with the following commands: "hello", "how are you", "weather", and "bye".';
}
// More custom commands
}
4. Adding More Interactivity
a. Personalized Responses
You could allow users to enter their name, and the bot can remember it for future conversations:
let userName = '';
function getBotResponse(userMessage) {
const lowerMessage = userMessage.toLowerCase();
if (lowerMessage.includes('my name is')) {
userName = userMessage.split('is ')[1];
return `Nice to meet you, ${userName}! How can I assist you today?`;
}
if (userName) {
return `Hello again, ${userName}! How can I help you today?`;
}
return 'Hello! How can I assist you today?';
}
b. Emotions or Emoji Responses
You can make the chatbot more expressive by adding emojis to responses:
function getBotResponse(userMessage) {
const lowerMessage = userMessage.toLowerCase();
if (lowerMessage.includes('happy')) {
return 'I’m glad to hear you’re happy! 😊';
} else if (lowerMessage.includes('sad')) {
return 'I’m sorry you feel sad. 😔 Let me know if you need help!';
}
// Other emotional responses
}
5. Adding External Data (Advanced)
If you want to make your chatbot more dynamic, you can fetch real-time data, like weather updates or news headlines, from APIs. For instance, you can integrate a weather API into the chatbot using fetch:
function getWeather(city) {
const apiKey = 'YOUR_API_KEY';
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`)
.then(response => response.json())
.then(data => {
const weather = data.weather[0].description;
addMessage(`The weather in ${city} is ${weather}.`, 'bot-message');
});
}
function getBotResponse(userMessage) {
const lowerMessage = userMessage.toLowerCase();
if (lowerMessage.includes('weather')) {
const city = userMessage.split(' ')[1]; // Assumes the user types "weather [city name]"
getWeather(city);
return 'Checking the weather...';
}
return 'Sorry, I didn’t understand that.';
}
This is an advanced feature requiring access to external services like APIs and more complex JavaScript logic.
6. Other Enhancements
You can further enhance your chatbot by adding:
User Authentication: Ask for and store user credentials.
Voice Input/Output: Integrate the Web Speech API to allow voice input and output.
Chat History: Save and display previous chat messages in a persistent manner.
Summary of Customization Options:
CSS Customization: Modify the chatbot’s layout, colors, fonts, and button styles.
JavaScript Customization: Alter bot responses, add more features (like personalized responses or commands), and simulate human-like conversations.
Advanced Features: Integrate APIs, voice input/output, and more dynamic content.
Conclusion:
This chatbot is simple, interactive, and mimics basic conversation by checking keywords in the user's message and providing pre-defined responses. The code combines HTML for structure, CSS for styling, and JavaScript for interactivity and logic. By following these steps and modifying the code, you can create a chatbot that fits your specific requirements and provides a personalized user experience.