Search Autocomplete Feature with HTML, CSS & JavaScript
30 DAYS 30 PROJECT CHALLENGE
Day #04
Project Overview
Search Autocomplete Feature is a beginner-friendly project that uses HTML, CSS, and JavaScript. It provides search suggestions in real time as the user types into the search input. The suggestions are filtered from a given array of skills and technologies and displayed below the search bar. This project highlights the matching parts of the suggested searches, which makes it easier to understand what the suggestion is about. Additionally, users can click their desired search suggestion or use arrow keys and Enter key to choose their option.
This project is perfect for beginners who want to learn how to implement a search feature with filtering, DOM-manipulation, keyboard interactions and optimize performance. The app showcases how a search bar with suggestions can be made more interactive with JavaScript.
Key Features
- Real-Time Search Suggestions: As users are typing in the search field, the app filters relevant items and displays them as suggestions without a separate search button.
- Dynamic Data Filtering: JavaScript compares the user input with the array elements and displays only those items that contain the matching value.
- Highlighted Matching Text: The matching text of every item is underlined to help the user easily see why the suggestion appears.
- Click-to-Select Suggestions: By clicking on a suggestion, the value is placed in the search field, and the suggestions list is closed.
- Keyboard Navigation: Arrow up/down keys can be used to navigate through the available suggestions.
- Enter Key Selection: After selecting a suggestion with the keyboard, the Enter key places the value in the search field.
- Debounce Functionality: The search implements a debounce function that waits before displaying the results to avoid excessive function calls while typing.
- Outside Click Detection: Clicking outside the search box closes the suggestions.
- Clean and Responsive UI: The center search box with a scrollable suggestions list is easy to use and appears on different screen sizes.
What You'll Learn
- Understand how to listen for user input using JavaScript events.
- Learn how to filter data stored inside a JavaScript array.
- Practice updating HTML elements dynamically.
- Understand how
filter()can be used for search functionality. - Learn how to create elements using
document.createElement(). - Practice handling click events on dynamically created elements.
- Understand how regular expressions can highlight matching text.
- Learn how keyboard events can improve user interaction.
- Practice working with Arrow Up, Arrow Down, and Enter keys.
- Understand how debounce functions can improve performance.
- Learn how to detect clicks outside a specific element.
- Practice connecting HTML, CSS, and JavaScript to build an interactive search feature.
HTML Code
HTML creates the basic structure of the Search Autocomplete Feature. First, the style.css file is linked inside the <head> section so CSS can control the appearance and layout of the search interface. The main content is placed inside the .search-box container. Inside this container, an <h2> element displays the project heading, <input> element with the searchInput ID allows users to type their search query, autocomplete="off" attribute prevents the browser from displaying its own saved suggestions.
Below the input field, the <ul> element with the suggestions ID provides an empty container where JavaScript dynamically creates and displays matching search suggestions. Finally, the script.js file is loaded at the bottom of the <body> so JavaScript can access the input and suggestion elements and provide the autocomplete functionality.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Search Autocomplete</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="search-box">
<h2>Search Autocomplete</h2>
<input
type="text"
id="searchInput"
placeholder="Search skills..."
autocomplete="off"
/>
<ul id="suggestions"></ul>
</div>
<script src="script.js"></script>
</body>
</html>
CSS Code
CSS controls the appearance and layout of the Search Autocomplete Feature. The universal selector applies box-sizing and a consistent font to the elements and the body uses Flexbox to place the search box in the center of the page, .search-box class styles the main container by adding a white background, fixed width, padding, rounded corners, and a shadow, input field takes the full width of the container and receives a border and rounded corners. When the user clicks the input, the :focus selector changes its border color.
The <ul> element styles the suggestions area and adds a maximum height with vertical scrolling. Each <li> represents a search suggestion and the :hover and .active styles highlight suggestions during mouse or keyboard interaction. Finally, the .highlight class makes the matching search text bold and visually different from the rest of the suggestion.
* {
box-sizing: border-box;
font-family: "Segoe UI", sans-serif;
}
body {
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background: #042453;
}
.search-box {
background: #fff;
width: 340px;
padding: 25px;
border-radius: 12px;
box-shadow: 0 20px 40px rgba(0,0,0,0.15);
}
h2 {
text-align: center;
margin-bottom: 15px;
}
input {
width: 100%;
padding: 12px;
border-radius: 8px;
border: 1px solid #ccc;
outline: none;
}
input:focus {
border-color: #4f46e5;
}
ul {
list-style: none;
margin-top: 8px;
padding: 0;
max-height: 200px;
overflow-y: auto;
border-radius: 8px;
}
li {
padding: 10px;
cursor: pointer;
background: #f9fafb;
border-bottom: 1px solid #e5e7eb;
}
li:hover,
li.active {
background: #eef2ff;
}
.highlight {
color: #4f46e5;
font-weight: bold;
}
Javascript Code
JavaScript provides the main autocomplete functionality. First, it selects the search input and suggestions container from the HTML and the items array stores the skills and technologies that can appear as search suggestions, debounce() function delays the search slightly while the user is typing, helping avoid unnecessary updates. When the input event occurs, the showSuggestions() function reads the entered value, converts it to lowercase, and filters the items array to find matching results.
For every matching item, JavaScript creates an <li> element and adds it to the suggestions list and the highlightMatch() function uses a regular expression to highlight the matching part of each suggestion. Clicking a suggestion places its value inside the input field.
The keyboard event listener allows users to move through suggestions using the Arrow keys and select one with Enter. Finally, a document click event detects clicks outside the search box and clears the suggestions list automatically.
const input = document.getElementById("searchInput");
const suggestions = document.getElementById("suggestions");
const items = [
"HTML",
"CSS",
"JavaScript",
"React",
"Angular",
"Vue",
"Node.js",
"Express",
"MongoDB",
"Firebase",
"Bootstrap",
"Tailwind CSS",
"Python",
"Django",
"Flask"
];
let activeIndex = -1;
let debounceTimer;
/* Debounce function */
function debounce(callback, delay) {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(callback, delay);
}
/* Handle input */
input.addEventListener("input", () => {
debounce(showSuggestions, 200);
});
function showSuggestions() {
const value = input.value.toLowerCase();
suggestions.innerHTML = "";
activeIndex = -1;
if (!value) return;
const filtered = items.filter(item =>
item.toLowerCase().includes(value)
);
filtered.forEach(item => {
const li = document.createElement("li");
li.innerHTML = highlightMatch(item, value);
li.addEventListener("click", () => {
input.value = item;
suggestions.innerHTML = "";
});
suggestions.appendChild(li);
});
}
/* Highlight matching text */
function highlightMatch(text, value) {
const regex = new RegExp(`(${value})`, "gi");
return text.replace(regex, `<span class="highlight">$1</span>`);
}
/* Keyboard navigation */
input.addEventListener("keydown", e => {
const listItems = document.querySelectorAll("#suggestions li");
if (e.key === "ArrowDown") {
activeIndex++;
if (activeIndex >= listItems.length) activeIndex = 0;
}
if (e.key === "ArrowUp") {
activeIndex--;
if (activeIndex < 0) activeIndex = listItems.length - 1;
}
if (e.key === "Enter" && activeIndex > -1) {
input.value = listItems[activeIndex].innerText;
suggestions.innerHTML = "";
return;
}
listItems.forEach(item => item.classList.remove("active"));
if (listItems[activeIndex]) {
listItems[activeIndex].classList.add("active");
}
});
/* Close suggestions on outside click */
document.addEventListener("click", e => {
if (!e.target.closest(".search-box")) {
suggestions.innerHTML = "";
}
});
Related Projects
Day 2 : Multi-Step FormĀ
A step-by-step form with progress tracking and input validation.
Concepts: DOM manipulation, form validation, progress tracking.
Day 11 : User Profile Card Generator
Generates a user profile card dynamically from form inputs.
Concepts: User input processing, live UI generation, state-based rendering.
Day 13 : Like / Dislike Counter System
Interactive counter system that tracks user likes and dislikes in real time.
Concepts: User interaction handling, state tracking, dynamic count updates, UI feedback.