...

/

Building Live Search Functionality: Part I

Building Live Search Functionality: Part I

Learn to create a live search feature using JavaScript.

Search functionality

If we look at our website, the navigation bar contains a search icon. From this lesson, we will start building the search functionality. We want the search results to be displayed dynamically. The pages on our site are displayed using PHP files. Once a page has loaded, JavaScript is used to make any changes to it without refreshing the page.

We want to provide the live search option to the user which is interactive and engaging as it provides immediate feedback reducing wait time. When the search icon gets clicked, an overlay panel with a search box will open. The results appear on the overlay panel as soon as the user finishes typing. This provides the users with quick feedback and the ability to refine the search in real time.

With the Excellence theme folder open in VS Code, open the terminal in VS Code by clicking the "View" option and choosing "Terminal." Run the start script using the npm run start command. The start script will watch for any changes in the code and recompile it.

Go to the src folder inside the theme folder and open the index.js file. This is where we load the different modules and create objects from the classes. The src folder has a modules folder which contains JavaScript modules of our site like Counter.js, Slider.js, and Menu.js. The index.js file is reproduced below:

import "../assets/css/style.css"
import "../assets/css/interior.css"
// Modules
import Menu from "./modules/Menu"
import Slider from "./modules/Slider"
import Counter from "./modules/Counter"
// Creating objects
var menu = new Menu()
var slider = new Slider()
var counter = new Counter()
index.js file

The Search.js file

Separating the JavaScript code into modules improves readability and maintainability of the code. To implement the search functionality we will create a new file in the modules folder. Let’s name the file Search.js.

There are a number of ways to go about implementing the search functionality. We will use object oriented JavaScript and create a class called Search.

class Search {
}
Search class
...