Creating Search Bar With Autocomplete Search Suggestions In JavaScript
Published: 2023-06-10 06:43:50

Hello, Coder! You will discover how to create a  **[Search Bar With Autocomplete](https://www.codewithrandom.com/2022/11/02/search-bar-with-autocomplete-javascript/)** and Search Suggestions using JavaScript in this blog. You should be comfortable with using form components to build a search bar because this project will be of intermediate difficulty. In this blog, we will walk you through the procedure step-by-step, if you don't know how to make a search bar.

As you can see in the above preview a search input box. It functions as a field for the user to enter a query or search word to look up related information in the database. a pattern or feature that displays query recommendations and anticipates the remaining letters in a user's input.

As you input in the search bar on the webpage in this software (Search Bar with Auto-complete Search Suggestions), an autocomplete box appears with many suggestions for how your inquiry might be finished. This indicates that your question is supported by a number of suggestions.

I hope you have a general idea of what the project entails. In our article, we will go over this project step by step.

The three sections of this task are the HTML, CSS, and Javascript sections. In these parts, we'll learn how to create search box with autocomplete feature project step-by-step.

**Step1: Adding some basic HTML Code**

HTML stands for HyperText Markup Language. This is a markup language. Its main job is to give our project structure. We will provide our project structure by utilising this markup language. So let's look at our HTML code.

We start with the HTML file. First, copy the code below and paste it into your HTML file inside your IDE.
```
<html lang="en" dir="ltr">
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://kit.fontawesome.com/1cf483120b.js" crossorigin="anonymous"></script>	<script defer
        src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAi0RCj8aLdKFX-cvYkW6kDveuaUlMnpes&libraries=places&callback=initMap">
        </script>
</head>

<body>
    <div class="wrapper">
        <div class="search-input">
            <a href="" target="_blank" hidden></a>
               <input type="text" placeholder="Type to search..">
               <div class="autocom-box">
               </div>
               <div class="icon"><i class="fas fa-search"></i></div>
        </div>
    </div>
    <script src="index.js"></script>
</body>
</html>
```
We must update certain links before we start our search box project. In order to complete this project, we had to connect the three distinct files we utilised for our HTML, CSS, and JavaScript. In order to achieve this, kindly place links to our CSS inside the header.

All of the links for the various icons that we utilised in our project must be embedded. You must include the Javascript file inside the HTML's body if you want to link it to our HTML file.
```
//Head section 
<link rel="stylesheet" href="style.css"> 
<script src="https://kit.fontawesome.com/1cf483120b.js" crossorigin="anonymous"></script>	
<script defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAi0RCj8aLdKFX-cvYkW6kDveuaUlMnpes&libraries=places&callback=initMap"></script> 
//Body Section 
<script src="index.js"></script>
```
Now let's Add the structure for our Searchbox with autocomplete feature.

We'll use the basic html elements to add the structure of our searchbox.

Using the div tag, we will design a wrapper class that will act as a container for our searchbox.
Now that we have created a hyperlink using an anchor link, we can search the content.
We will create an input box with type as "text" .
Now we'll make a div tag that will be utilised to provide text suggestions when the user fills into the search field.
Using the font-awesome class we will add an search icon inside our searchbox.

We don’t require anything else to build the structure for our image editor. Now that we are using CSS, we will style our image editor. But let’s look at our structure first.

**Step2: Adding CSS Code**

Cascading Style Sheets (CSS) is a markup language for describing the presentation of a document written in HTML or XML. CSS, like HTML and JavaScript, is a key component of the World Wide Web.

Now we will look at our CSS code.
```
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap");
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}

body {
  background: #644bff;
  padding: 0 20px;
}

::selection {
  color: #fff;
  background: #664aff;
}

.wrapper {
  max-width: 450px;
  margin: 150px auto;
}

.wrapper .search-input {
  background: #fff;
  width: 100%;
  border-radius: 5px;
  position: relative;
  box-shadow: 0px 1px 5px 3px rgba(0, 0, 0, 0.12);
}

.search-input input {
  height: 55px;
  width: 100%;
  outline: none;
  border: none;
  border-radius: 5px;
  padding: 0 60px 0 20px;
  font-size: 18px;
  box-shadow: 0px 1px 5px rgba(0, 0, 0, 0.1);
}

.search-input.active input {
  border-radius: 5px 5px 0 0;
}

.search-input .autocom-box {
  padding: 0;
  opacity: 0;
  pointer-events: none;
  max-height: 280px;
  overflow-y: auto;
}

.search-input.active .autocom-box {
  padding: 10px 8px;
  opacity: 1;
  pointer-events: auto;
}

.autocom-box li {
  list-style: none;
  padding: 8px 12px;
  display: none;
  width: 100%;
  cursor: default;
  border-radius: 3px;
}

.search-input.active .autocom-box li {
  display: block;
}
.autocom-box li:hover {
  background: #efefef;
}

.search-input .icon {
  position: absolute;
  right: 0px;
  top: 17px;
  height: 55px;
  width: 55px;
  text-align: center;
  line-height: 55px;
  font-size: 20px;
  color: #644bff;
  cursor: pointer;
}
```
After we’ve added the CSS code, we’ll go over it step by step. To save time, you can simply copy this code and paste it into your IDE. Let us now examine our code step by step.

We will be adding some basic styling to our Image editor, but you guys can try new styling and share your code in the comments, which will help other people to think out of the box. you will be able to style the image editor own your own.

**Step1:** First, we’ll use the import link to add the Poppins typeface from Google Fonts. We will set the box-sizing to the border box and the margin and padding to “zero” using the universal selector. Using the font-family attribute, Poppins is selected as the font family.

We will now style the body of our webpage using the body. We have added a 20px padding and using the backround properpty we will add a blue background to our search box.
```
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap");
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}

body {
  background: #644bff;
  padding: 0 20px;
}

::selection {
  color: #fff;
  background: #664aff;
}
```
**Step2:** We will now style the container for our search box. We will use the wrapper class to set the maximum width of the element to 450px, and we will use the margin property to add margins of 150px to the top and bottom and auto to the left and right.

The width is set to 100% and the background colour is set to "white" using the class selector (.search-input). We will add a border-radius of 5px using the border-radius property, and the position will be set to relative. We'll also give our search box container a box shadow.
```
.wrapper {
  max-width: 450px;
  margin: 150px auto;
}

.wrapper .search-input {
  background: #fff;
  width: 100%;
  border-radius: 5px;
  position: relative;
  box-shadow: 0px 1px 5px 3px rgba(0, 0, 0, 0.12);
}
```
**Step3:** We'll now style the search box and search icon. The width and height are both set to 55 pixels and 100%, respectively. The padding for our searchbox is set to 60px on the left, 20px on the right, and 0px on the top and bottom. The border is set to "none." The font-size attribute is used to set the font size to 18px.

Our icon's position is set to absolute, with a 17px distance from the top and a 0px distance to the right. We will centre the text by using the text-align property and setting the icon's height and width to each 55px. The icon's hue is changed to blue.
```
.search-input input {
  height: 55px;
  width: 100%;
  outline: none;
  border: none;
  border-radius: 5px;
  padding: 0 60px 0 20px;
  font-size: 18px;
  box-shadow: 0px 1px 5px rgba(0, 0, 0, 0.1);
}

.search-input.active input {
  border-radius: 5px 5px 0 0;
}

.search-input .autocom-box {
  padding: 0;
  opacity: 0;
  pointer-events: none;
  max-height: 280px;
  overflow-y: auto;
}

.search-input.active .autocom-box {
  padding: 10px 8px;
  opacity: 1;
  pointer-events: auto;
}

.autocom-box li {
  list-style: none;
  padding: 8px 12px;
  display: none;
  width: 100%;
  cursor: default;
  border-radius: 3px;
}

.search-input.active .autocom-box li {
  display: block;
}
.autocom-box li:hover {
  background: #efefef;
}

.search-input .icon {
  position: absolute;
  right: 0px;
  top: 17px;
  height: 55px;
  width: 55px;
  text-align: center;
  line-height: 55px;
  font-size: 20px;
  color: #644bff;
  cursor: pointer;
}
```
## Step3: Javascript Search Bar With Suggestions Code:-
```
let suggestions = [
  // ABC Normal Letters
  "Channel",
  "Codewithrandom",
  "Google",
  "Google Fonts",
  "Google Plus",
  "Google Drive",
  "Github",
  "CSS HTML JS",
  "TEnLOcRAFT",
  "CodePen Website",
  "YouTube",
  "YouTuber",
  "YouTube Channel",
  "Blogger",
  "Bollywood",
  "Vlogger",
  "Vechiles",
  "Facebook",
  "Freelancer",
  "Facebook Page",
  "Israel Hyom?",
  "YNet",
  "MineCraft",
  "Fortnite",
  "GTA",
  "GTA 2",
  "GTA 3",
  "GTA 4",
  "GTA V",
  "GTA 6",
  "Search Bar With AutoComplete || Eitan &mdash; CodePen",
  "Designer",
  "Developer",
  "Web Designer",
  "Web Developer",
  "Login Form in HTML & CSS",
  "How to learn HTML & CSS",
  "How to learn JavaScript",
  "How to became Freelancer",
  "How to became Web Designer",
  "How to start Gaming Channel",
  "How to start YouTube Channel",
  "What does HTML stands for?",
  "What does CSS stands for?",
  "Python",
  "Udemy",
  // Symbols Codes
  "&--SymbolCode--;",
  "&copy;",
  "&reg;",
  "&euro;",
  "&trade;",
  "&larr;",
  "&uarr;",
  "&rarr;",
  "&darr;",
  "&spades;",
  "&clubs;",
  "&hearts;",
  "&diams;",
  "&Alpha;",
  "&Beta;",
  "&Gamma;",
  "&Delta;",
  "&Epsilon;",
  "&Zeta;",
  "&copysr;",
  "⅁",
  "&sect;",
  "&alefsym;",
  "&beth;",
  "&gimel;",
  "&daleth;",
];

// getting all required elements
const searchWrapper = document.querySelector(".search-input");
const inputBox = searchWrapper.querySelector("input");
const suggBox = searchWrapper.querySelector(".autocom-box");
const icon = searchWrapper.querySelector(".icon");
let linkTag = searchWrapper.querySelector("a");
let webLink;

// if user press any key and release
inputBox.onkeyup = (e) => {
  let userData = e.target.value; //user enetered data
  let emptyArray = [];
  if (userData) {
    icon.onclick = () => {
      webLink = "https://www.google.com/search?q=" + userData;
      linkTag.setAttribute("href", webLink);
      console.log(webLink);
      linkTag.click();
    };
    emptyArray = suggestions.filter((data) => {
      //filtering array value and user characters to lowercase and return only those words which are start with user enetered chars
      return data.toLocaleLowerCase().startsWith(userData.toLocaleLowerCase());
    });
    emptyArray = emptyArray.map((data) => {
      // passing return data inside li tag
      return (data = "<li>" + data + "</li>");
    });
    searchWrapper.classList.add("active"); //show autocomplete box
    showSuggestions(emptyArray);
    let allList = suggBox.querySelectorAll("li");
    for (let i = 0; i < allList.length; i++) {
      //adding onclick attribute in all li tag
      allList[i].setAttribute("onclick", "select(this)");
    }
  } else {
    searchWrapper.classList.remove("active"); //hide autocomplete box
  }
};

function select(element, event) {
  let selectData = element.textContent;
  inputBox.value = selectData;
  icon.onclick = () => {
    webLink = "https://www.google.com/search?q=" + selectData;
    linkTag.setAttribute("href", webLink);
    linkTag.click();
  };
  searchWrapper.classList.remove("active");
}

function showSuggestions(list) {
  let listData;
  if (!list.length) {
    userValue = inputBox.value;
    listData = "<li>" + userValue + "</li>";
  } else {
    listData = list.join("");
  }
  suggBox.innerHTML = listData;
}
```
We will first create a array suggestion which will store the many words which will be suggested to the user when a user type any keyword inside the searchbar.
```
let suggestions = [
  // ABC Normal Letters
  "Channel",
  "Codewithrandom",
  "Google",
  "Google Fonts",
  "Google Plus",
  "Google Drive",
  "Github",
  "CSS HTML JS",
  "TEnLOcRAFT",
  "CodePen Website",
  "YouTube",
  "YouTuber",
  "YouTube Channel",
  "Blogger",
  "Bollywood",
  "Vlogger",
  "Vechiles",
  "Facebook",
  "Freelancer",
  "Facebook Page",
  "Israel Hyom?",
  "YNet",
  "MineCraft",
  "Fortnite",
  "GTA",
  "GTA 2",
  "GTA 3",
  "GTA 4",
  "GTA V",
  "GTA 6",
  "Search Bar With AutoComplete || Eitan &mdash; CodePen",
  "Designer",
  "Developer",
  "Web Designer",
  "Web Developer",
  "Login Form in HTML & CSS",
  "How to learn HTML & CSS",
  "How to learn JavaScript",
  "How to became Freelancer",
  "How to became Web Designer",
  "How to start Gaming Channel",
  "How to start YouTube Channel",
  "What does HTML stands for?",
  "What does CSS stands for?",
  "Python",
  "Udemy",
  // Symbols Codes
  "&--SymbolCode--;",
  "&copy;",
  "&reg;",
  "&euro;",
  "&trade;",
  "&larr;",
  "&uarr;",
  "&rarr;",
  "&darr;",
  "&spades;",
  "&clubs;",
  "&hearts;",
  "&diams;",
  "&Alpha;",
  "&Beta;",
  "&Gamma;",
  "&Delta;",
  "&Epsilon;",
  "&Zeta;",
  "&copysr;",
  "⅁",
  "&sect;",
  "&alefsym;",
  "&beth;",
  "&gimel;",
  "&daleth;",
];
```
We'll now make some constant variables to store the values of all the HTML elements we'll pick for the document. the queryselector() method. Additionally, we will create two variables using the let keyword because, unlike creating variables using constants, where we can modify a variable's value at any time, using the let keyword allows us to do so immediately after creation.
```
// getting all required elements
const searchWrapper = document.querySelector(".search-input");
const inputBox = searchWrapper.querySelector("input");
const suggBox = searchWrapper.querySelector(".autocom-box");
const icon = searchWrapper.querySelector(".icon");
let linkTag = searchWrapper.querySelector("a");
let webLink;
```
As the user pushes and releases any key, an event is launched using the onkeyup event. Using the e.target property, it targets the user value, and we create an empty variable.

Now, as soon as the user writes the word he wants to search for and clicks the search icon, Google.com is concatenated with the input and the results are displayed in a new window.

The array value will now be filtered based on the first character, and the user will see it. After that, we will compare the array value to the user data.
```
  if (userData) {
    icon.onclick = () => {
      webLink = "https://www.google.com/search?q=" + userData;
      linkTag.setAttribute("href", webLink);
      console.log(webLink);
      linkTag.click();
    };
    emptyArray = suggestions.filter((data) => {
      //filtering array value and user characters to lowercase and return only those words which are start with user enetered chars
      return data.toLocaleLowerCase().startsWith(userData.toLocaleLowerCase());
    });
    emptyArray = emptyArray.map((data) => {
      // passing return data inside li tag
      return (data = "<li>" + data + "</li>");
    });
    searchWrapper.classList.add("active"); //show autocomplete box
    showSuggestions(emptyArray);
    let allList = suggBox.querySelectorAll("li");
    for (let i = 0; i < allList.length; i++) {
      //adding onclick attribute in all li tag
      allList[i].setAttribute("onclick", "select(this)");
    }
  } else {
    searchWrapper.classList.remove("active"); //hide autocomplete box
  }
};
```
Now, we'll build a function called select that takes two arguments: element and event. The data will be selected inside the function using the inputBox.value, and when the user clicks it, a link to the icon.onlclick method will be created.

In a similar vein, we'll develop a function that we'll demonstrate in the HTML element proposal.
```
function select(element, event) {
  let selectData = element.textContent;
  inputBox.value = selectData;
  icon.onclick = () => {
    webLink = "https://www.google.com/search?q=" + selectData;
    linkTag.setAttribute("href", webLink);
    linkTag.click();
  };
  searchWrapper.classList.remove("active");
}

function showSuggestions(list) {
  let listData;
  if (!list.length) {
    userValue = inputBox.value;
    listData = "<li>" + userValue + "</li>";
  } else {
    listData = list.join("");
  }
  suggBox.innerHTML = listData;
}
```
Now we've completed searchbox with autocomplete feature using HTML , CSS & javascript. I hope you understood the whole project. Let's take a look at our Live Preview.

Final Output Of Search Bar With Autocomplete Search Suggestions:-
Live Preview Of Search Bar With Autocomplete:-

Now We have Successfully created our **[Search Bar With Autocomplete](https://www.codewithrandom.com/2022/11/02/search-bar-with-autocomplete-javascript/)** Search Suggestions In JavaScript. You can use this project directly by copying into your  IDE. WE hope you understood the project , If you any doubt feel free to comment!!

If you find out this Blog helpful, then make sure to search code with random on google for Front End Projects with Source codes and make sure to Follow the Code with Random Instagram page.

follow : codewithrandom

Written By : Arun

Code By: Eitan