How to Build a Chatbot Using Wikipedia in HTML, CSS, and JavaScript

 

Build Your Own Chatbot with Wikipedia and JavaScript (No Backend Needed)

Chatbots have become an essential part of the modern web. From customer service assistants to fun conversational bots, they can provide instant answers, guide users, and even act as mini search engines. But did you know that you can build your own chatbot using just HTML, CSS, and JavaScript—without any complex backend servers?

In this tutorial, we will walk through the complete process of creating a simple yet powerful Wikipedia chatbot. This chatbot will allow users to ask questions, and the bot will fetch relevant answers directly from Wikipedia’s API. By the end, you’ll have a working chatbot that feels intelligent and can be customized further to suit your needs.

This blog is written in a detailed, step-by-step manner. Whether you are a beginner learning web development or an advanced coder experimenting with APIs, this guide will give you a solid foundation.




Why Build a Wikipedia Chatbot?

Before we dive into the code, let’s understand why we’re building a Wikipedia chatbot specifically.

  1. Free Knowledge Source
    Wikipedia is one of the largest free knowledge bases on the internet. Its API provides structured data, making it perfect for chatbot integration.

  2. No Database Needed
    Instead of manually storing information, the chatbot can pull answers directly from Wikipedia, saving you time and resources.

  3. Hands-On API Practice
    Using the Wikipedia API teaches you how to work with REST APIs, JSON responses, and asynchronous JavaScript (fetch, promises, async/await).

  4. Great Learning Project
    Building a chatbot with HTML, CSS, and JavaScript helps you practice frontend development, DOM manipulation, and API integration in a practical way.


Tools and Technologies You’ll Use

We will use three core technologies:

  • HTML → To structure the chatbot interface (chat window, input field, send button).

  • CSS → To style the chatbot, making it look clean and user-friendly.

  • JavaScript → To add interactivity, fetch data from Wikipedia, and display responses.

Additionally, we will use the Wikipedia REST API to fetch summaries of topics.


Step 1: Setting Up the Project

Create a folder on your computer (e.g., wikipedia-chatbot). Inside it, create three files:

  • index.html

  • style.css

  • script.js

This structure keeps your code clean and organized.


Step 2: Writing the HTML

Our chatbot needs a chat window, a message display area, and an input box with a button.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Wikipedia Chatbot</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="chat-container"> <div class="chat-header">Wikipedia Chatbot</div> <div class="chat-box" id="chat-box"></div> <div class="chat-input"> <input type="text" id="user-input" placeholder="Ask me anything..."> <button id="send-btn">Send</button> </div> </div> <script src="script.js"></script> </body> </html>

This creates the skeleton of our chatbot:

  • chat-header → Title bar

  • chat-box → Area where conversation messages appear

  • chat-input → Input field + button




Step 3: Adding CSS for Styling

Now let’s make our chatbot look good with CSS.

/* style.css */ body { font-family: Arial, sans-serif; background: #f2f2f2; display: flex; justify-content: center; align-items: center; height: 100vh; } .chat-container { width: 400px; background: white; border-radius: 12px; box-shadow: 0 4px 10px rgba(0,0,0,0.2); display: flex; flex-direction: column; overflow: hidden; } .chat-header { background: #2c3e50; color: white; padding: 15px; text-align: center; font-size: 18px; } .chat-box { flex: 1; padding: 10px; overflow-y: auto; background: #fafafa; } .chat-message { margin: 8px 0; padding: 10px; border-radius: 10px; max-width: 75%; } .user-message { background: #3498db; color: white; align-self: flex-end; } .bot-message { background: #ecf0f1; color: #2c3e50; align-self: flex-start; } .chat-input { display: flex; border-top: 1px solid #ccc; } .chat-input input { flex: 1; border: none; padding: 12px; font-size: 16px; } .chat-input button { background: #3498db; border: none; color: white; padding: 12px 20px; cursor: pointer; }

Now the chatbot looks like a neat messaging app.




Step 4: Adding JavaScript for Functionality

Let’s handle user input, display messages, and fetch data from Wikipedia.

// script.js const chatBox = document.getElementById("chat-box"); const userInput = document.getElementById("user-input"); const sendBtn = document.getElementById("send-btn"); // Function to add message to chat function addMessage(message, className) { const msgDiv = document.createElement("div"); msgDiv.classList.add("chat-message", className); msgDiv.innerText = message; chatBox.appendChild(msgDiv); chatBox.scrollTop = chatBox.scrollHeight; // Auto scroll } // Function to fetch Wikipedia summary async function fetchWikipedia(query) { const apiUrl = `https://en.wikipedia.org/api/rest_v1/page/summary/${encodeURIComponent(query)}`; try { const response = await fetch(apiUrl); if (!response.ok) throw new Error("No data found"); const data = await response.json(); return data.extract || "Sorry, I couldn't find anything on that."; } catch (error) { return "Oops! Something went wrong. Try another question."; } } // Event listener for button click sendBtn.addEventListener("click", async () => { const query = userInput.value.trim(); if (query === "") return; addMessage(query, "user-message"); userInput.value = ""; const botReply = await fetchWikipedia(query); addMessage(botReply, "bot-message"); }); // Enter key support userInput.addEventListener("keypress", (e) => { if (e.key === "Enter") sendBtn.click(); });

Step 5: Testing the Chatbot

Open your index.html file in a browser. Try typing:

The bot will fetch summaries directly from Wikipedia and display them in the chat.




Step 6: Improving the Chatbot

Our chatbot works, but let’s make it smarter:

  1. Greeting Message
    Add a welcome message when the page loads.

window.onload = () => { addMessage("Hello! I'm a Wikipedia Chatbot. Ask me about any topic!", "bot-message"); };
  1. Loading Indicator
    Show “Typing…” while fetching data.

addMessage("Typing...", "bot-message"); const botReply = await fetchWikipedia(query); chatBox.lastChild.innerText = botReply; // Replace last message
  1. Clickable Wikipedia Links
    Provide links for full articles.

return `${data.extract}\n\nRead more: ${data.content_urls.desktop.page}`;
  1. Error Handling
    Handle queries that don’t match Wikipedia articles gracefully.


Step 7: Styling Enhancements

To make the chatbot more attractive, you can add:

Example dark mode CSS:

body.dark { background: #181818; } body.dark .chat-container { background: #2c2c2c; color: #fff; }

And toggle with JavaScript:

document.body.classList.toggle("dark");

Step 8: Challenges and Considerations

Building a chatbot is fun, but you’ll encounter some challenges:

  • Ambiguous Queries → Wikipedia may not always return expected results.

  • API Rate Limits → Avoid too many requests in a short time.

  • Long Answers → Wikipedia summaries can be lengthy; consider truncating them.

  • User Experience → Always show meaningful feedback (like loading indicators).


Step 9: Real-World Applications

A Wikipedia chatbot might seem like a fun project, but the same principles apply to professional use cases:

  • Customer Support Bots (FAQ retrieval)

  • Educational Tools (instant explanations for students)

  • Healthcare Assistants (fetch medical info)

  • Tourism Bots (quick facts about places)

By swapping the Wikipedia API with another API, you can build a specialized chatbot for any industry.


SEO Tips for Your Chatbot Project Blog

If you’re writing a blog (like this one) about your chatbot project, here are some SEO tips:


Conclusion

You just built a fully functional chatbot using Wikipedia with nothing more than HTML, CSS, and JavaScript. This project is an excellent way to practice frontend development, API integration, and UI/UX design.

The beauty of this chatbot is its simplicity—you don’t need servers, databases, or AI models. Yet, with just a few enhancements, you can turn it into a powerful tool that provides instant knowledge to users.

Now that you understand the fundamentals, try customizing your chatbot further:

  • Add voice recognition with the Web Speech API.

  • Make it multilingual using Wikipedia’s language options.

  • Connect it with other APIs for more advanced functionality.

The possibilities are endless. Happy coding! 🚀

Post a Comment

2 Comments