Building a Simple Chatbot for Your Website
Creating a chatbot for your website can be a game-changer in how you interact with visitors. Whether you’re looking to automate customer support, gather feedback, or guide visitors through your site, a chatbot can do it all. In this blog, we’ll walk through how to build a basic chatbot using JavaScript. This chatbot will be able to answer simple questions and provide predefined responses to users.
What You’ll Need
- Basic knowledge of HTML and JavaScript: Understanding of how to create web pages and run JavaScript.
- Text editor: Any text editor like VS Code, Sublime Text, or Atom will work.
- Web browser: To test and view your chatbot.
Step 1: Setting Up Your Project
Create a new folder on your computer and name it chatbot
. Inside this folder, create two files: index.html
and chatbot.js
.
index.html
<!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>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="chatbox">
<textarea id="chatlog" cols="30" rows="10" disabled></textarea>
<input type="text" id="userinput" placeholder="Ask me something..." onkeypress="handleKeyPress(event)">
<div id="typing" style="display: none;">Bot is typing...</div>
<button onclick="getResponse()">Send</button>
</div>
<script src="chatbot.js"></script>
</body>
</html>
This HTML provides a basic user interface for the chatbot with a textarea for the chat log, an input box for the user to type their questions, and a button to send their query.
Step 2: Writing the JavaScript
Open your chatbot.js
file. Here’s how you can write a basic function to handle user input and provide a response.
chatbot.js
function getResponse() {
var input = document.getElementById('userinput').value.trim();
console.log("Input received:", input); // Check what input is received
if (input !== "") {
addMessage(input, 'user');
document.getElementById('userinput').value = ''; // Clear input field
showTyping();
setTimeout(function() {
var response = processInput(input.toLowerCase());
console.log("Response generated:", response); // Check what response is generated
addMessage(response, 'bot');
hideTyping();
}, 1000); // Simulated delay for bot response
}
}
function addMessage(message, sender) {
var messageDiv = document.createElement('div');
messageDiv.classList.add('message');
messageDiv.textContent = message;
if (sender === 'user') {
messageDiv.classList.add('user-message');
} else {
messageDiv.classList.add('bot-message');
}
var chatlog = document.getElementById('chatlog');
chatlog.appendChild(messageDiv);
chatlog.scrollTop = chatlog.scrollHeight; // Auto-scroll to the latest message
}
function showTyping() {
document.getElementById('typing').style.display = 'block';
}
function hideTyping() {
document.getElementById('typing').style.display = 'none';
}
function handleKeyPress(event) {
if (event.keyCode === 13) { // 13 is the Enter key
event.preventDefault(); // Prevent default form submission
getResponse();
}
}
function processInput(input) {
console.log("Processing input:", input); // Debug input processing
if (input.includes("hello") || input.includes("hi")) {
return "Hello! How can I help you today?";
} else if (input.includes("help")) {
return "I can assist you with various queries. Ask me about site navigation, customer support, or more!";
} else if (input.includes("shipping")) {
return "Shipping takes 3-5 business days. You can track your shipping status on your profile.";
} else if (input.includes("return") || input.includes("refund")) {
return "You can return items within 30 days of receipt. Refunds are processed within 7 business days.";
} else if (input.includes("thank you") || input.includes("thanks")) {
return "You're welcome! Is there anything else I can help with?";
} else {
return "Sorry, I'm not sure how to help with that. Could you try asking something else?";
}
}
This JavaScript listens for clicks on the ‘Send’ button, processes the user’s input, and adds the conversation to the chat log. The processInput
function is designed to respond based on keywords in the user’s message.
Enhancing Your Simple Chatbot with CSS and More Dynamic Responses
To make your chatbot more visually appealing and interactively sophisticated, we’ll add some CSS styling and expand the range of responses it can handle. This tutorial will guide you through enhancing the visual appeal of the chatbot interface and improving the bot’s response system beyond basic keyword matching.
What You’ll Need
- Additional file: Create a new file named
styles.css
in your project folder.
Step 1: Adding CSS for Styling
In your chatbot
project folder, create a new file called styles.css
. This CSS will style the chat interface to make it more user-friendly and visually attractive.
styles.css
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f4f4f9;
}
#chatbox {
width: 300px;
background-color: white;
box-shadow: 0 0 10px 2px rgba(0,0,0,0.1);
padding: 20px;
display: flex;
flex-direction: column;
gap: 10px;
}
textarea {
height: 150px;
padding: 10px;
border: 1px solid #ccc;
resize: none;
}
input, button {
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 14px;
}
button {
background-color: #007bff;
color: white;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
#typing {
color: #888;
font-style: italic;
}
#chatlog {
min-height: 150px;
max-height: 500px; /* Sets maximum height before scrolling */
overflow-y: auto; /* Enables scrolling */
display: flex;
flex-direction: column;
gap: 5px;
padding: 10px;
background-color: #fff;
border: 1px solid #ccc;
}
.message {
padding: 8px;
border-radius: 10px;
max-width: 80%;
}
.user-message {
align-self: flex-end;
background-color: #007bff;
color: white;
}
.bot-message {
align-self: flex-start;
background-color: #f1f1f1;
color: #333;
}
Link this CSS file to your index.html
by adding the following line in the <head>
section:
<link rel="stylesheet" href="styles.css">
Step 3: Testing Your Chatbot
Open your index.html
file in a web browser. You should see a simple interface where you can type questions and receive responses from the chatbot. Test different inputs to see how your chatbot responds.
Conclusion
Building a simple chatbot is just the beginning. As you expand your chatbot’s capabilities, you can provide more value to your website visitors, enhancing their experience and your website’s functionality. Remember, the key to a successful chatbot is continuous testing and improvement based on user feedback and needs.
This basic tutorial sets up a foundation that you can build upon with more sophisticated tools and technologies as you grow more comfortable with the basics. Happy coding!