DEV Community

AshleeLarrick
AshleeLarrick

Posted on

How to Create a Search Bar in JavaScript with the DOM

Introduction

Have you ever wanted to make a simple search bar for your website or app and don't know where to start? This blog will break it down in the easiest way possible to get you from start to finish!

Backend setup for index.js

If you don't have it already, you'll want to start by installing Node.js to your computer. Next, create a new folder for your project and navigate into that folder using the terminal. Once inside the new project folder initialize the Node.js by running the npm init command. After, you'll run the npm install command.

Create db.json File

After the backend folder is created and everything is initialized, you'll want to crate a new file within that project folder and name it db.json. This file will hold the backend data for your search bar. Add in all the JSON content you want and save the file. For example:

{
    "fish" : [     
         {
            "seasons" : ["Fall", "Summer", "Spring", "Winter"],
            "name" : "Woodskip",
            "weather" : "Any Weather",
            "time" : "Any Time",
            "location" : "Secret Woods",
            "image" : "https://stardewvalleywiki.com/mediawiki/images/9/97/Woodskip.png"
        },
        {
            "seasons" : ["Fall", "Summer", "Spring", "Winter"],
            "name" : "Void Salmon",
            "weather" : "Any Weather",
            "time" : "Any Time",
            "location" : "Witch's Swamp",
            "image" : "https://stardewvalleywiki.com/mediawiki/images/a/ad/Void_Salmon.png"
        },
        {
            "seasons" : ["Fall", "Summer", "Winter"],
            "name" : "Red Snapper",
            "weather" : "Rain",
            "time" : "6am- 7pm",
            "location" : "Ocean",
            "image" : "https://stardewvalleywiki.com/mediawiki/images/d/d3/Red_Snapper.png"
        },
        {
            "seasons" : ["Fall", "Winter"],
            "name" : "Midnight Carp",
            "weather" : "Any Weather",
            "time" : "10pm - 2am",
            "location" : "Mountain Lake",
            "image" : "https://stardewvalleywiki.com/mediawiki/images/3/33/Midnight_Carp.png"
        },        
        {
            "seasons" : ["Fall", "Winter"],
            "name" : "Tiger Trout",
            "weather" : "Any Weather",
            "time" : "6am - 7pm",
            "location" : "River",
            "image" : "https://stardewvalleywiki.com/mediawiki/images/0/01/Tiger_Trout.png"
        },
...
    ]
}
Enter fullscreen mode Exit fullscreen mode

After you've created the db.json file you'll need to create a index.html, index.js and index.css files. Leave these blank for now.

Start json-server

Make sure you're in the correct folder containing the db.json file and run the command json-server --watch db.json. This starts a server on http://localhost:3000.

Add localhost setup to index.js

Don't forget to add in the link to the URL above for your local host that you created, which leads to all information placed in the db.json file.
[Image description]

HTML

Navigate to the index.html file and within the body of the code and create a div and set the class to equal a string called "container". This container will represent the search box. Within that same div you'll create a form element and set the class to a unique string. Inside that form element you can create a header element for the search bar. Set the class to equal to another unique string (ex: fish-header) and add in some text. That same div block will also be the div that you place all of the input values such as type, name, value, placeholder and class.
[Image description]

index.js

Back in the index.js file you'll want to create an event listener which listens to keypress events.
[Image description]
Following the event listener, you'll also need to create a function, define it, and add event as an argument, which is pulled from the event listener. That function will need to hold an if statement with the event.key being equal to Enter. This prevents non-'Enter' key presses from calling the function. The If statement will also need to hold a preventDefault call to prevent the page from reloading. Next you'll use the fetch method with the URL to make the request to the server and pull the data back to the index.js file.
[Image description]
Next, you'll want to declare a variable and set that with the value as event.target.value. This value will contain the text from the search box. To make it easier to use add on the .toLowerCase() method to convert the string to lower case letters. A For loop is needed after. It will loop through all the data from your db.json file. Inside this loop, you will need an if statement with data[index]. This accesses the object at the given index in the data array. The .name accesses the name property of the object at the given index adding another .toLowerCase(). Next, throw in the .startsWith() method that will check if the lowercase value of the name property starts with the lowercase value of what is returned from the search bar (ex: Fish). Below the if statement, you'll want to create a new HTML li element and assign it to a variable named li the document represents the HTML document currently loaded in the browser and the .createElement() method creates a new HTML element with the tag name specified as an argument.
[Image description]
Declare another variable named p and assign it using document.createElement('p') to create a paragraph element. The p.innerHTML = data[index].name sets the innerHTML property of the newly created p element to the name of the object in the data array. Lastly, use li.appendChild() to append the newly created element to the list item we created before.
[Image description]

index.css

In the index.css file you can style the text and search bar as little or much as you'd like. The .container will be the editor for the search bar and the title attached to it.
[Image description]
The .input-text will be the returned list of the items searched for, there you can also change up the text color or text font.
[Image description]

With all this new information given to you, you'll now be able to build a search bar with ease!

Top comments (0)