A searchbar is a popular UI element that many modern websites utilize. If you are building a site that contains any type of data, you may want your users to be able to search for specific items.

There are many ways you can build a searchbar. You can create complex searchbars that return results based on multiple filters, such as a name or date. Existing libraries can help you implement a searchbar without building it from scratch.

However, you can also create a simple searchbar using vanilla JavaScript, that compares a user's input against a list of strings.

Your website should include an input box for your users to enter the text that they want to search for. One way to do this is to use an input tag, and style it to look like a searchbar.

  1. Create a folder to store your website. Inside the folder, create an HTML file named index.html.
  2. Populate your file with the basic structure of an HTML document. If you are not familiar with HTML, there are many HTML code examples you can learn to help you get up to speed.
            <!doctype html>
    <html lang="en-US">
      <head>
        <title>Searchbar</title>
      </head>
      <body>
        <div class="container">
          <!-- Webpage content goes here-->
        </div>
      </body>
    </html>
  3. Inside the container class div, add an input tag. This will allow the user to type in the text that they would like to search for. Whenever they enter a new character, your website will call the search() function. You will create this function in later steps.
            <div class="container">
        <h2>Search Countries</h2>
        <input id="searchbar" autocomplete="off" onkeyup="search()" type="text"\n name="search" placeholder="What are you looking for?">
    </div>
    The autocomplete attribute ensures a browser will not add its own dropdown based on previous search terms.
  4. In the same folder as your index.html file, create a new CSS file called styles.css.
  5. Populate the file with styling for the overall webpage and the searchbar:
            body {
      margin: 0;
      padding: 0;
      background-color: #f7f7f7;
    }
    * {
      font-family: "Arial", sans-serif;
    }
    .container {
      padding: 100px 25%;
      display: flex;
      flex-direction: column;
      line-height: 2rem;
      font-size: 1.2em;
      color: #202C39;
    }
    #searchbar {
       padding: 15px;
       border-radius: 5px;
    }
    input[type=text] {
       -webkit-transition: width 0.15s ease-in-out;
       transition: width 0.15s ease-in-out;
    }
  6. In index.html, add a link to your CSS file inside the head tag and underneath the title tag:
            <link rel="stylesheet" href="styles.css">
        
  7. Open the index.html file in a web browser, and view the UI of your searchbar.
    HTML website with searchbar in browser

Before the user can search, you will need to create a list of available items that they can search for. You can do this with an array of strings. A string is one of the many data types you can use in JavaScript, and can represent a sequence of characters.

You can dynamically create this list using JavaScript, as the page is loading.

  1. Inside index.html, underneath the input tag, add a div. This div will display a dropdown that will contain a list of items that match what the user is searching for:
            <div id="list"></div>
        
  2. In the same folder as your index.html file and styles.css file, create a new file called script.js.
  3. Inside script.js, create a new function called loadSearchData(). Inside the function, initialize an array with a list of strings. Keep in mind that this is a small static list. A more complex implementation will have to take into account searching through larger datasets.
            function loadSearchData() {
      // Data to be used in the searchbar
      let countries = [
        'Australia',
        'Austria',
        'Brazil',
        'Canada',
        'Denmark',
        'Egypt',
        'France',
        'Germany',
        'USA',
        'Vietnam'
      ];
    }
  4. Inside loadSearchData() and underneath the new array, get the div element that will display the matching search items to the user. Inside the list div, add an anchor tag for each data item in the list:
            // Get the HTML element of the list
    let list = document.getElementById('list');
    // Add each data item as an <a> tag
    countries.forEach((country)=>{
        let a = document.createElement("a");
        a.innerText = country;
        a.classList.add("listItem");
        list.appendChild(a);
    })
  5. In the body tag of index.html, add the onload event attribute to call the new loadSearchData() function. This will load the data as the page is loading.
            <body onload="loadSearchData()">
        
  6. In index.html, before the body tag ends, add a script tag to link to your JavaScript file:
            <body onload="loadSearchData()">
        <!-- Your webpage content -->
        <script src="script.js"></script>
    </body>
  7. In styles.css, add some styling to the dropdown list:
            #list {
       border: 1px solid lightgrey;
       border-radius: 5px;
       display: block;
    }
    .listItem {
       display: flex;
       flex-direction: column;
       text-decoration: none;
       padding: 5px 20px;
       color: black;
    }
    .listItem:hover {
       background-color: lightgrey;
    }
  8. Open index.html in a web browser to view your searchbar and the list of available search results. The search functionality does not work yet, but you should see the UI that it will use:
    HTML website searchbar with unfiltered search list

Now that you have a searchbar and a list of strings for users to search, you can add the search functionality. As the user types into the searchbar, only certain items in the list will display.

  1. In styles.css, replace the styling for the list to hide the list by default:
            #list {
       border: 1px solid lightgrey;
       border-radius: 5px;
       display: none;
    }
  2. In script.js, create a new function called search(). Keep in mind that the program will call this function every time the user enters or removes a character from the searchbar. Some applications will need trips to a server to fetch information. In such cases, this implementation could slow down your UI. You may need to modify the implementation to take this into account.
            function search() {
        // search functionality goes here
    }
  3. Inside the search() function, get the HTML div element for the list. Also get the HTML anchor tag elements of each item inside the list:
            let listContainer = document.getElementById('list');
    let listItems = document.getElementsByClassName('listItem');
  4. Get the input that the user entered into the searchbar:
            let input = document.getElementById('searchbar').value
    input = input.toLowerCase();
  5. Compare the user's input to each item in the list. For example, if the user enters "a", the function will compare if "a" is inside "Australia", then "Austria", "Brazil", "Canada", and so on. If it matches, it will display that item in the list. If it does not match, it will hide that item.
            let noResults = true;
    for (i = 0; i < listItems.length; i++) {
        if (!listItems[i].innerHTML.toLowerCase().includes(input) || input === "") {
            listItems[i].style.display="none";
            continue;
        }
        else {
            listItems[i].style.display="flex";
            noResults = false;
        }
    }
  6. If there are no results at all in the list, hide the list completely:
            listContainer.style.display = noResults ? "none" : "block";
        
  7. Click on the index.html file to open it in a web browser.
    HTML website with searchbar in browser
  8. Start typing into the searchbar. As you type, the list of results will update to only display matching results.
    HTML searchbar with matching results

Using a Searchbar to Search for Matching Results

Now that you know how to create a searchbar with string selection, you can add more functionality.

For instance, you can add links to your anchor tags to open different pages depending on the result the user clicks. You can change your searchbar to search through more complex objects. You can also modify the code to work with frameworks like React.