As a Shopify developer, you’ve probably come across a lot of different types of projects.
And you’ll also know that a lot of them require features that are not natively offered by Shopify like a page search bar.
Sure Shopify themes come with a search bar, but not a search bar that works only within a page, which is very helpful when you have a lot of items to display.
Here are some of its many use cases:
Need a feature like this on your project but are not sure where to get started?
If so, follow this tutorial.
This tutorial does not include steps in adding the items on your page nor creating a page from scratch.
If you are completely new to Shopify and need help with these, check the list of guides I’ve gathered for you below before following this tutorial.
In this step you simply need to write your html code just like the code in the screenshot. You may style it later using CSS.
Whether you are new to JavaScript or have been using it for a while, you might find the steps quite a lot, since there are many things to consider in building this feature.
This is why I highly suggest you view the actual code sample I made on CodePen below as you follow and understand the steps on this page.
You may also view the actual pen here.
See the Pen How to Add a Page Search Bar on Shopify by RDC (@reddelacruzdev) on CodePen.
Now, there are quite a few things that need to be done for this function to run.
So, first things first let us try to understand the things that need to happen every time a user types in the input.
Now that we've established the things needed in the function, here are the things that it should have when you write the code:
1. First, your function needs to have a ‘setTimeout’ function when declaring a variable for the input’s value.
This is so that this does not happen on every single letter we type. It would be annoying for a user to get a response when they are not even done typing yet.
Remember, we are using an ‘input’ event listener here.
2. Next, in step 1 where we declared our variables, a variable for your setTimeout should have been declared without a value.
We declare our variable outside our function so that we can access it for our ‘clearTimeout.’
We use 'clearTimeout' before we even run the ‘setTimeout.’ Feel free to research more about it if you think you need to understand this concept better.
3. Redeclare our ‘setTimeout’ variable but now with a value which is the ‘setTimeout’ code.
So what are included in this ‘setTimeout’ function?
We use the ‘toLowerCase’ method to avoid any letter case problems. This way, we are only checking if the characters are the same and not the letter case.