What’s a Search Bar?
Okay, so we probably all know what a search bar is at this point but let me quickly explain. A search bar is an input box that appears on browsers, websites, and applications. It takes in a user’s search query and allows you to search for some type of information.
A search engine is the software system behind the scenes that handles searches on the web.
Did you know the world wide web was entirely indexed by hand prior to the first web search engines? I can probably write a whole article about the history of search engines but today we’re just going to be building a basic search bar for a web application.
Building a Search Bar
To begin to create our search bar feature we should think about several concepts that go into a working version of it. We know that we’re going to need an empty search bar that takes in user input. We also need a way to capture that input and handle it to start finding what the user is searching for while they are typing it in. To find and render this data to the user we should store whatever type of data is being searched. In this case, we’re going to be working with a social app that allows users to search their list of friends out using a search bar.
To start building out our search bar we’re going to need to set up the HTML first to make it appear on our app. We can build out the basic structure to get something showing up on the page.
Let’s check out what our search feature is looking like after setting everything up with HTML.
Not the best-looking search app yet but we’re getting somewhere. We’ll give it some styling to make it more user-friendly.
This should give us a much nicer-looking app to work with.
nameelements from the DOM and store them in variables
Add an event listener on the searchInput to listen for keyup events
Get user input once the event is triggered
Search name elements and convert text to lowercase for case insensitive comparisons
Compare names to the search query using the string method includes()
Update name element styles to display matching names
It works! Now our search bar will give us the closest matching name results based on what letter characters we’re typing in.
Search bars are a common feature of most web and mobile applications. They usually appear somewhere at the top corner of a web page and persist across the website for user convenience. Depending on the specifics of your application, search bars can be a great addition to it. For example, if your app holds a lot of information for the user it can greatly improve the user experience.
Top comments (2)
Tip: Use type
searchinstead of type
inputfor the search, so it provides better hints to the browser about the usage (making it more accessible, in mobile it will show the magnifying glass icon and so on):
Also you might want to check the datalist element, which is designed for autocomplete hints.
Try putting two of these in the same page, then have fun rewriting the whole thing.