top of page
  • Writer's pictureDark CSS

Create an Autocomplete Search Bar using HTML CSS JavaScript

Introduction:

In this tutorial, we'll learn how to create an autocomplete search box using HTML, CSS, and JavaScript. Create an Autocomplete Search Bar using HTML CSS JavaScript suggests possible matches to users as they type, improving search efficiency and user experience on websites. We'll build a stylish and functional search box that provides real-time suggestions based on predefined queries. A visually appealing interface with a search input and embedded search icon. Dynamic suggestions that appear beneath the input field as the user types. Keyboard navigation for selecting suggestions using arrow keys and Enter.

Now setup files to start writing our project logics index.html, style.css and script.js



Autocomplete Search Bar


Html Code Explanation

 <!-- Wrapper div to center and style the search box -->
  <div class="wrapper">
    <form action="" autocomplete="off"> <!-- Form element for the search box with autocomplete off -->
      <div class="autocomplete">
        <input type="text" placeholder="Search here.." id="myInput"> <!-- Input field for search with placeholder text and unique ID -->
      </div>
      <button type="submit"><ion-icon name="search-outline"></ion-icon></button> <!-- Search button with search icon -->
    </form>
  </div>

  <!-- Linking external JavaScript files -->
  <script src="script.js"></script>

.wrapper class Contains the entire search box interface. Applied styling to center and style the search box.

Form Element used for containing the search input.

Autocomplete Input: Type set to "text" for user input. Placeholder text ("Search here..") for guiding users. Unique ID (myInput) to target this input in JavaScript.

Search icon: Type set to "submit" to trigger form submission. Contains an <ion-icon> for the search icon.


CSS Code Explanation

Of course! Let's break down each part of the CSS code used for styling the autocomplete search box step by step.

/* Importing Google Font for styling */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap');

/* General styling for all elements */
* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
  font-family: 'Poppins', sans-serif; /* Setting custom font for the entire page */
}
/* Grid display for centering content vertically and horizontally */
html, body {
  display: grid;
  height: 100%;
  place-items: center;
  background: #1e1e1e; /* Background color for the entire page */
}

@import url: This imports the Google Font 'Poppins' with different weights (400, 500, 600) for use throughout the page.

*: This selects all elements in the HTML document. box-sizing: border-box; ensures that padding and border are included in the element's total width and height, preventing unexpected layout issues. padding: 0; resets padding to zero for all elements. margin: 0; resets margin to zero for all elements. font-family: 'Poppins', sans-serif; sets the default font for all text content to 'Poppins', and if 'Poppins' is unavailable, it falls back to a generic sans-serif font.

display: grid, sets the display property of the html and body elements to a grid layout, allowing easy vertical and horizontal centering of content.

height: 100%, ensures that the html and body elements occupy the full height of the viewport.

place-items: center, centers the content both vertically and horizontally within the grid container (viewport). background: #1e1e1e, sets the background color of the entire page to a dark shade.


/* Styling for the wrapper div */
.wrapper {
  position: relative;
  width: 640px;
  padding: 10px;
  background: #292929;
  border-radius: 10px;
  box-shadow: 0px 2px 10px rgba(0,0,0,0.24); 
  border: 2px solid rgba(7, 7, 7, 0.12);
  overflow: hidden;
}

position: relative sets the positioning context for the, .wrapper element to relative, allowing child elements to be positioned relative to this container, width: 640px sets a fixed width of 640 pixels for the .wrapper element, padding: 10px adds 10 pixels of padding inside the .wrapper element. background: #292929 sets the background color of the .wrapper element to a slightly lighter shade of black (#292929), border-radius: 10px applies a border-radius of 10 pixels, rounding the corners of the .wrapper element, box-shadow: 0px 2px 10px rgba(0,0,0,0.24) adds a subtle box-shadow effect to the .wrapper element for a raised appearance, border: 2px solid rgba(7, 7, 7, 0.12) sets a 2-pixel solid border around the .wrapper element with a low opacity color for a subtle border effect, overflow: hidden hides any content that overflows the boundaries of the .wrapper element.


/* Styling for the autocomplete container */
.wrapper .autocomplete {
  width: 100%;
  position: relative;
}
/* Styling for the search input field */
.wrapper .autocomplete input {
  height: 50px;
  width: calc(100% - 60px);
  outline: none;
  border: none;
  color: rgb(228, 222, 222); 
  background-color: #2d2d2d; 
  padding: 0 15px; /* Padding inside the input */
  letter-spacing: 1px;
  border: 1px solid solid rgb(63, 63, 63);
  border-radius: 10px 0 0 10px;
}

width: 100%; sets the width of the .autocomplete container to 100% of its parent element (.wrapper), position: relative;: Sets the positioning context for the .autocomplete container to relative.

Targets the <input> element within the .autocomplete container, height: 50px;: Sets the height of the input field to 50 pixels, width: calc(100% - 60px);: Sets the width of the input field to 100% minus 60 pixels (to accommodate the search button next to it), outline: none;: Removes the default focus outline, border: none;: Removes the default border, color: rgb(228, 222, 222);: Sets the text color to a light gray (#e4dede), background-color: #2d2d2d;: Sets the background color of the input field to a dark gray (#2d2d2d), padding: 0 15px;: Adds 0 pixels of padding on top and bottom, and 15 pixels of padding on the left and right sides inside the input field, letter-spacing: 1px;: Sets the letter spacing of the text inside the input field to 1 pixel, border: 1px solid solid rgb(63, 63, 63);: Sets a 1-pixel solid border around the input field with a darker gray color (#3f3f3f).

border-radius: 10px 0 0 10px;: Applies rounded corners only to the left side of the input field (top-left and bottom-left).


Video Tutorial




JavaScript Code Explanation


Autocomplete Function

function autocomplete(inp, arr) {
    var currentFocus;
    
}

The autocomplete function initializes the autocomplete behavior on the provided input element (inp). It sets up event listeners for input events (typing), keyboard events (navigation and selection), and clicks outside the input field (to close the suggestion list).


Event Listener for Input

inp.addEventListener("input", function (e) {
    var val = this.value;
    closeAllLists();
    if (!val) { return false; }
    currentFocus = -1;
    var autocompleteContainer = document.createElement("DIV");
    autocompleteContainer.setAttribute("id", this.id + "autocomplete-list");
    autocompleteContainer.setAttribute("class", "autocomplete-items");
    this.parentNode.appendChild(autocompleteContainer);
    for (var i = 0; i < arr.length; i++) {
        // Logic to filter and display autocomplete suggestions
    }
});

This event listener (input event) triggers whenever the user types into the input field. It clears any existing autocomplete suggestion lists (closeAllLists()). If the input value is empty, it returns early.

Creates a new <div> element (autocompleteContainer) to hold autocomplete suggestions.

Loops through the arr array to filter and display matching autocomplete suggestions based on the current input value (val).


Generating Autocomplete Suggestions

if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
    // Create a new suggestion div
    var suggestionDiv = document.createElement("DIV");
    // Highlight the matching part of the suggestion
    suggestionDiv.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
    suggestionDiv.innerHTML += arr[i].substr(val.length);
    // Store the full suggestion as a hidden input value
    suggestionDiv.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
    // Event listener to handle suggestion selection
    suggestionDiv.addEventListener("click", function (e) {
        // Fill the input field with the selected suggestion
        inp.value = this.getElementsByTagName("input")[0].value;
        // Close the autocomplete list
        closeAllLists();
    });
    // Append the suggestion div to the autocomplete container
    autocompleteContainer.appendChild(suggestionDiv);
}

This section generates individual autocomplete suggestions within the for loop. Checks if each query in the arr array starts with the current input value (val). Creates a new <div> (suggestionDiv) for each matching suggestion. Highlights the matching part of the suggestion using <strong> tags. Adds a hidden <input> field to store the full suggestion text.

Sets up a click event listener on each suggestion to fill the input field with the selected suggestion and close the autocomplete list.


keydown Event Listener

inp.addEventListener("keydown", function (e) {
    var autocompleteItems = document.getElementById(this.id + "autocomplete-list");
    if (autocompleteItems) {
        autocompleteItems = autocompleteItems.getElementsByTagName("div");
        if (e.keyCode == 40) {  // Arrow down key
            // Move focus down the suggestion list
            currentFocus++;
        } else if (e.keyCode == 38) {   // Arrow up key
            // Move focus up the suggestion list
            currentFocus--;
        } else if (e.keyCode == 13) {   // Enter key
            e.preventDefault();
            if (currentFocus > -1) {
                // Simulate a click on the focused suggestion
                autocompleteItems[currentFocus].click();
            }
        }
    }
});

Handles keyboard interactions (keydown event) within the input field. Retrieves the autocomplete suggestion container (autocompleteItems). If arrow keys (keyCode 40 for down, keyCode 38 for up) are pressed, it adjusts the currentFocus variable to navigate through the suggestion list.

If the Enter key (keyCode 13) is pressed, it prevents the default behavior (form submission), and if there's a focused suggestion (currentFocus > -1), it simulates a click on the focused suggestion to fill the input field and close the autocomplete list.


Closing Autocomplete Lists

function closeAllLists(elmnt) {
    var autocompleteItems = document.getElementsByClassName("autocomplete-items");
    for (var i = 0; i < autocompleteItems.length; i++) {
        if (elmnt != autocompleteItems[i] && elmnt != inp) {
            // Remove autocomplete suggestion list
            autocompleteItems[i].parentNode.removeChild(autocompleteItems[i]);
        }
    }
}

The closeAllLists function is responsible for closing all open autocomplete suggestion lists.

Retrieves all elements with class autocomplete-items. Iterates through each autocomplete suggestion list and removes it from the DOM, except for the current input field (inp) and its associated suggestion list.


Document Click Event Listener

document.addEventListener("click", function (e) {
    // Close autocomplete lists when clicking outside the input field
    closeAllLists(e.target);
});

Listens for click events (click event) anywhere on the document. Calls closeAllLists function with the clicked target (e.target) to close autocomplete suggestion lists if the click is outside the input field or its associated suggestion list.


Initializing Autocomplete

autocomplete(document.getElementById("myInput"), queries);

Initializes the autocomplete functionality on a specific input element (<input id="myInput">) using the autocomplete function.

Passes the input element (document.getElementById("myInput")) and an array of predefined queries (queries) to set up autocomplete behavior for that input field.


Conclusion:

Overall, this project teaches how to make a smart search box using HTML, CSS, and JavaScript. HTML sets up the basic structure of the search box, CSS makes it look nice and organized, and JavaScript adds the clever part where it suggests search options as you type. This project is easy to modify and use in websites, making searches more user-friendly and engaging. By learning these technologies together, beginners can create interactive search features that improve the overall experience for users.


Download Source Code



Autocomplete Search Bar
.zip
Download ZIP • 3KB

Dark CSS

bottom of page