Search Bar With Autocomplete using HTML JavaScript

Search bar with autocomplete search suggestions in JavaScript

Let us create a Search Bar With Autocomplete Search Suggestions In JavaScript

Hello, developers! You will discover how to create a Ā Search Bar With Autocomplete 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.

Search Bar With Autocomplete Search Suggestions In JavaScript
Search Bar With Autocomplete using HTML & JavaScript

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.

50+ HTML, CSS & JavaScript Projects With Source Code

  • As you give 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 a search box with an 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 utilizing 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 utilized for our HTML, CSS, and JavaScript. In order to achieve this, kindly place links to our CSS inside the header.

Build a Quiz App With HTML , CSS, and JavaScript

All of the links for the various icons that we utilized 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 the autocomplete feature.

We’ll use the basic HTML elements to add the structure of our search box.

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

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.

Output:

Search Bar With Autocomplete Search Suggestions In JavaScript
Search Bar With Autocomplete using HTML & JavaScript

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.

Simple Portfolio Website Using Html And Css With Source Code

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.

Ecommerce Website Using HTML CSS and Javascript Source Code

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 think out of the box. you will be able to style the image editor on your own.

Step 1:

  • 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 background properly 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;
}
Search Bar With Autocomplete Search Suggestions In JavaScript
Search Bar With Autocomplete using HTML & Css

Step 2:

  • 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 color 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);
}
Search Bar With Autocomplete using HTML & JavaScript
Search Bar With Autocomplete using HTML & JavaScript

Step 3:

  • 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 search 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.

Weather App Using Html, Css, And JavaScriptĀ 

  • Our icon’s position is set to absolute, with a 17px distance from the top and a 0px distance to the right.
  • We will align the text in the center 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;
}

Search Bar With Autocomplete using HTML & JavaScript

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 an array of suggestions that will store the many words that will be suggested to the user when a user types any keyword inside the search bar.

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.

Gym Website Using HTML and CSS With Source Code

// 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.

100+ JavaScript Projects With Source Code ( Beginners to Advanced)

ADVERTISEMENT

In a similar vein, we’ll develop a function that we’ll demonstrate in the HTML element proposal.

ADVERTISEMENT

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 the search box with an autocomplete feature using HTML, CSS, and JavaScript. I hope you understood the whole project. Let’s take a look at our Live Preview.

ADVERTISEMENT

Final Output Of Search Bar With Autocomplete Search Suggestions:-

Live Preview Of Search Bar With Autocomplete:-


Now We have Successfully created our sSearch Bar With Autocomplete Search Suggestions In JavaScript. You can use this project directly by copying it into yourĀ  IDE. WE hope you understood the project, If you have any doubts feel free to comment!!

ADVERTISEMENT

If you find this javascript search bar with suggestions Blog helpful, then make sure to search codewithrandom on Google for Front End Projects with Source codes and make sure to Follow the Code with Random Instagram page.

ADVERTISEMENT

Written By: @Arun
Code By: @Eitan


Leave a Reply