DEV Community

Vikas Choubey
Vikas Choubey

Posted on • Updated on

Designing an Autocomplete UI Component πŸ”

In the ever-evolving landscape of web development, creating intuitive user interfaces is paramount. One such interface element that has become indispensable is the autocomplete component. In this blog post, we'll explore the process of designing an autocomplete UI component that enables users to effortlessly enter a search term, presents a list of search results in a convenient popup, and empowers them to select a result.
Let's dive in! πŸš€

Baby dives in pool

The Magic of Autocomplete✨

Autocomplete UI components have revolutionized user experiences by making search more efficient and user-friendly. Before we delve into the nuts and bolts of implementation, let's establish the essential features that constitute an effective autocomplete:

Text Input Box 🎹: This familiar text input field serves as the gateway for users to enter their search queries.

Search Results Popup ⚑: A dynamic popup or dropdown that appears as soon as users start typing. It showcases a list of suggested results, providing instant feedback.

Search Result Items 🎯: Each item in the popup should be informative, with a clear indication of the matched portion of the result. Visual cues like distinct text colors or background shades aid in result differentiation.

Navigation 🏹: Users should be able to navigate through the search results using keyboard arrows (up and down) and mouse clicks for a seamless experience.

Selection πŸ‘‰: When a user selects a search result, it should fill the text input field, making it easy to confirm the selection. This interaction should feel intuitive.

Dismissal ❌: The popup should vanish when users click outside it, press the 'Esc' key, make a selection, or clear the input field.

Real-time Filtering ⏰: Results should update in real-time as the user types, eliminating the need for a manual search button. Implement a slight delay before making a new request to the server to reduce unnecessary requests.

The Code Unveiled πŸ’»πŸ‘¨β€πŸ’»

Code Unveiled

Demo the code here.

Now, let's take a look at a simplified implementation using HTML, CSS, and JavaScript:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Autocomplete Example</title>
 <link src='./styles.css' rel='stylesheet'/>
</head>
<body>
    <div id="autocomplete-container">
        <input type="text" id="search-input" placeholder="Search...">
        <div id="search-results"></div>
    </div>

    <script src='./script.js></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS

 /* Basic CSS styles for the autocomplete */
 #autocomplete - container {
     position: relative;
     width: 300 px;
 }
 #search - input {
     width: 100 % ;
     padding: 10 px;
 }
 #search - results {
         position: absolute;
         width: 100 % ;
         border: 1 px solid #ccc;
         max - height: 150 px;
         overflow - y: auto;
         display: none;
     }
     .result - item {
         padding: 5 px;
         cursor: pointer;
     }
     .result - item: hover {
         background - color: #f0f0f0;
     }       
Enter fullscreen mode Exit fullscreen mode

Javascript

 // Sample data (replace with your actual data source)
const data = [
    "Apple",
    "Banana",
    "Cherry",
    "Date",
    "Fig",
    "Grape",
    "Lemon",
    "Mango",
    "Orange",
    "Peach",
    "Pear",
    "Pineapple",
    "Strawberry",
    "Watermelon"
];

// Input element
const searchInput = document.getElementById("search-input");

// Results popup
const searchResults = document.getElementById("search-results");

// Function to filter and display results
function updateResults() {
    const query = searchInput.value.toLowerCase();
    const filteredData = data.filter(item => item.toLowerCase().includes(query));

    // Clear previous results
    searchResults.innerHTML = "";

    // Display new results
    filteredData.forEach(item => {
        // Create a div to hold each result
        const resultItem = document.createElement("div");
        resultItem.className = "result-item";
        resultItem.textContent = item;

        // Handle click on result item
        resultItem.addEventListener("click", () => {
            searchInput.value = item;
            searchResults.style.display = "none";
        });

        // Add each result div to the popup
        searchResults.appendChild(resultItem);
    });

    // Show/hide results popup
    searchResults.style.display = filteredData.length ? "block" : "none";
}

// Event listeners
searchInput.addEventListener("input", updateResults);
document.addEventListener("click", (event) => {
    if (event.target !== searchInput) {
        searchResults.style.display = "none";
    }
});
Enter fullscreen mode Exit fullscreen mode

Wrapping It Up 🎁

Implementing an autocomplete UI component from scratch is a rewarding endeavor that enhances the usability of web applications. By adhering to these design principles and dissecting the code, you can craft a potent and user-friendly autocomplete component. Feel free to customize and expand upon this example to cater to your project's unique requirements. πŸ› οΈ

So, why wait? Begin your journey to create an autocomplete component today, and provide your users with a delightful search experience! 🌟

Part 2 of this series: Debouncing

Connect with me on my:

LinkedIn
GitHub
Twitter

Top comments (0)