Search Bar with Auto Completion

Written by @phuang 3 December 2022

Search bar with auto completion is a nice feature to provide real-time results to a user based on their query. For instant, it can be used to show products on an ecommerce website. In this tutorial, we will fetch a list of first names from a URL and show the resulting names in real-time as the user types.

Code Snippet:

                                                
                                                <!-- this script is provided by www.javascriptfreecode.com coded by: Kerixa Inc. -->
<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Search Bar With AutoCompletion</title>

<!-- font awesome library include 4.7 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" integrity="sha512-5A8nwdMOWrSz20fDsjczgUidUBR8liPYU+WymTZP1lmY9G6Oc7HlZv156XqnsgNUzTyMefFTcsFH/tnJE/+xBg==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<!-- css styles -->
<style>
:root{
  margin: 0;
  padding: 0;
  font-family: arial, monospace;

}

*{
  box-sizing: border-box;
}

html, body{
  height: 100%;
  background-color: powderblue;
}

body{
  margin: 0 auto;
  padding: 0;

  display:flex;
  justify-content: center;
  align-items: flex-start;
}

.search_bar{
  display: flex;

}

.search_bar > div{
  padding: 0.25rem;

  background: white;
}

.search_bar input:focus{
  outline: none;
}


/* circular shadow and styles */
.search_bar input{
  outline: none;
  border: none;

}

.search_bar > div:first-child{
  border-top-left-radius: 50%;
  border-bottom-left-radius: 50%;
 
}


.search_bar > div:last-child{
  border-top-right-radius: 50%;
  border-bottom-right-radius: 50%;
  border: 0;
  outline: 0;

}

.search_bar > div{
  min-height: 1.5rem;
  min-width: 1.5rem;
}
.search_bar button {
  min-height: 1.5rem;
  min-width: 1.5rem;
  border-radius: 50%;
  outline: none;
  background: transparent;
  border: 0;
}
.search_bar button:hover{
  
  color: darkcyan;
}

.search_container{
  margin-top: 2rem;
}

.search_container > .search_results{

  background-color: white;
  margin-top: 0.5rem;
  padding: 1rem;
  border-radius: 1rem;
  font-size: 0.75rem;
  color: black;
}

hr{
  border: 0;
  border-top: 1px solid rgba(0,0,0,.1);
}

.d-none{
  display: none;
}


</style>
</head>

<body>


    <div class="search_container">
      <div class="search_bar">
        <div> <button class="js-search"> <i class="fa fa-search" aria-hidden="true"></i></button></div>
        <div><input class="js-type-search" type="text" placeholder="Search name..." /></div>
        <div></div>
      </div>

      <div class="search_results d-none js-results">
    
      </div>
    </div>



<script>


/*   

Tutorial Description

Search bar with auto completion is a nice feature to provide real-time results to a user based on their query. For instant, it can be used to show products on an ecommerce website. 

In this tutorial, we will fetch a list of first names from a URL and show the resulting names in real-time as the user types.

*/


let names = [];
const search_type = document.querySelector(".js-type-search");
const search_enter = document.querySelector(".js-search");
const results = document.querySelector(".js-results");
const results_counter = 7;

const load_names = () =>{
  try{

    fetch("https://raw.githubusercontent.com/dominictarr/random-name/master/first-names.txt").then(response => {

      if(response.status === 200){
       
        response.text().then(results => {
          
          names = results.split(/\r?\n/);
        })
      }
    })
  }
  catch(error){
    console.log(error);
  }
}

load_names();

function hideResultsPane(){
  
  const results = document.querySelector(".js-results");
  results.classList.add("d-none");
  results.innerHTML  = "";
    
}

if(search_type != null){

  
  search_type.addEventListener("input", event => {

    results.innerHTML = "";

    if( event.target.value.length > 0){

      let counter = 0;
      let data = [];

      const user_query = event.target.value.toLowerCase();

      // compare the user input name with the array of names based on match of the name from the left side
      for(let i = 0; i < names.length; i++){

        const name = names[i];

        if(name.length >= user_query.length){

          const name_to_compare = name.substring(0, user_query.length).toLowerCase();

          if(name_to_compare === user_query && counter < results_counter){
            data.push(name);
            counter++;
          }
        }
      }

      // populate the results pane
      if(data.length > 0){

        results.classList.remove("d-none");

        for(let i = 0; i < data.length; i++){

          const span = document.createElement("span");
          const hr = document.createElement("hr");
          span.textContent = data[i];
          
          if(i == (data.length - 1)){
            results.appendChild(span);
          
          }else{
            results.appendChild(span);
            results.appendChild(hr);

          }
        }
      }else{
        hideResultsPane();
      }
    }
 
  })


  search_type.addEventListener("keydown", event => {
    if(event.key === "Backspace" || event.code === "Backspace"){
      hideResultsPane();
    }
  })

}

</script>
</body>
</html><a target='_blank' href='www.javascriptfreecode.com' style='font-size: 8pt; text-decoration: none'>JavaScript Best Codes</a>                                                
                                            

Example:


About @phuang

Help desk analyst transitioning to a full-stack developer role. Hoping to learn and collaborate with everyone. Happy coding!

P

Comments


Here you can leave us commments. Let us know what you think about this code tutorial!

0 / 300

TRENDING POST
1
2
3
4
5
VISITORS
Online Users: 12
Recent Members: Estevan Belo, Shahmeer, coolcoco7, SmitaPatil25, owoboycute
advertisement 2