🔎 Building a Mini Search Bar with JavaScript

🔎 Building a Mini Search Bar with JavaScript

The Art of Real-Time Search with includes + filter + input event

Imagine a user…
They type J into the input.
The list updates instantly.
They type Ja… the list gets narrower.
They type Java… only “JavaScript” remains.

And in the background, you whisper:

“I built this with just 15 lines of JavaScript.” 😏

This article reveals the magic behind that moment.


🧠 1. Search Bar Logic (Seeing the Big Picture First)

Before writing any code, let’s clarify one thing:

What does a search bar actually do?

  • The user types something ✍️
  • JavaScript captures the input 🎯
  • It compares it with items in a list 🔍
  • Matching items are shown, others are hidden 🚪

So everything revolves around this trio:

  • input event → “What did the user type?”
  • includes() → “Does this text exist here?”
  • filter / condition → “Show or hide?”

Google does this on a billion-dollar scale.
We’re building the mini, cute, and educational version 😄


🧱 2. HTML – The Basic Structure (No Muscles Without a Skeleton)

<input 
  type="text" 
  id="searchInput" 
  placeholder="Search for a programming language..." 
/>

<ul id="languageList">
  <li>JavaScript</li>
  <li>Python</li>
  <li>Java</li>
  <li>TypeScript</li>
  <li>React</li>
  <li>Vue</li>
  <li>Angular</li>
</ul>

🔍 What Do We Have Here?

  • input
    → Where the user types
  • ul + li
    → The list we will filter

📌 We intentionally kept it simple.
Because the focus is not HTML — it’s JavaScript logic.


🎯 3. Enter JavaScript – Meeting the DOM

const searchInput = document.getElementById("searchInput");
const listItems = document.querySelectorAll("#languageList li");

🧠 What Did We Do?

  • Grabbed the input element
  • Selected all list items

Now JavaScript can control, hide, or show these elements.

🎈 Small but critical note:
querySelectorAll returns a NodeList.
It behaves like an array, but it’s not exactly one.


⚡ 4. input Event – Real-Time Magic ✨

searchInput.addEventListener("input", function () {
  console.log("User is typing...");
});

🎉 Why Is the input Event Awesome?

  • It runs on every keystroke
  • No need to press Enter
  • UX = 🧠 + ❤️

📌 Alternatives:

  • keyup → older but still used
  • change → triggers only when focus is lost (not what we want)

Search bar = input event
No debate 😄


🔤 5. What Did the User Type? (The value Truth)

const searchText = searchInput.value;

But here comes a big trap 🧨

"JavaScript".includes("javascript"); // false

😱 Because JavaScript is case-sensitive.


🛡️ 6. Escaping Case Sensitivity (The Golden Rule)

const searchText = searchInput.value.toLowerCase();

And for the list items:

const text = item.textContent.toLowerCase();

📌 Golden Rule:
Always normalize user input
(lowercase, trim, etc.)


❤️ 7. includes() – The Heart of the Search Bar

text.includes(searchText);

What Does It Do?

  • If it exists → true
  • If not → false

Simple.
Fast.
Readable.

includes() = “Does it exist?”
The detective’s magnifying glass 🔍


🎭 8. The Main Logic – Show / Hide Mechanism

searchInput.addEventListener("input", function () {
  const searchText = searchInput.value.toLowerCase();

  listItems.forEach(item => {
    const text = item.textContent.toLowerCase();

    if (text.includes(searchText)) {
      item.style.display = "block";
    } else {
      item.style.display = "none";
    }
  });
});


🧩 Breaking Down the Code

🔹 forEach

We loop through every list item:

“You, you, you… and you.” 😄


🔹 if (includes)

If there’s a match:

display: block

If not:

display: none

This is DOM manipulation in its simplest form.


🧪 9. A More Modern Approach – Using filter

searchInput.addEventListener("input", () => {
  const value = searchInput.value.toLowerCase();

  Array.from(listItems).filter(item => {
    item.style.display = item.textContent
      .toLowerCase()
      .includes(value)
      ? "block"
      : "none";
  });
});

📌 What did we learn here?

  • Array.from() → Converts NodeList into an array
  • Ternary operator → Cleaner, more elegant code

Someone seeing this code would say:

“This developer knows JavaScript.” 😎


🚀 10. Real-Life Use Cases

Where can this mini search bar be used?

  • 🛒 E-commerce product search
  • 👥 User lists
  • 📂 File filtering
  • 💬 Chat message search
  • 🎮 Game commands

A small example can open doors to big worlds.


💎 11. Professional Tips

🔹 Show everything when input is empty

if (searchText === "") {
  item.style.display = "block";
}

🔹 Add a “No results found” message

UX score +10 ⭐

🔹 For large lists

  • Use debounce
  • Avoid unnecessary DOM updates

🧠 Final Thoughts – What Did You Gain?

✔ input event
✔ includes()
✔ filter logic
✔ DOM control
✔ A real UI component

You’re no longer just someone who writes code —
you’re a frontend developer who thinks about the user experience 🦸‍♂️

Comments

No comments yet. Why don’t you start the discussion?

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir