Create A Simple JavaScript Filter — Tutorial
Earlier this year I was looking for a tutorial that would demonstrate & teach me at the same time how to create a filter with JavaScript. Since I needed to create a filter that filters products by price. Find a few videos on how to create the most basic filter with a search bar, which made it more difficult for me. The videos were not very helpful in this case since I wanted to create a filter by Price.
Therefore today I decided to create a tutorial that walks you through how to create this filter.
The common basic thing we need to be able to create this is to have a good foundation in HTML and JavaScript. We will also need to know a little bit about CSS the basics.
First, we’ll create a folder containing the following
- product.html
-product.js
-product.css
I chose to call it “product” since my filters will filter products that I will be using for selling.
We will start in HTML by creating a Section that will contain our filter options.
Inside this Section, we will put a Label that in my case will say “Price Filter:” you can name it as you want this will not affect anything we are just putting a name to the label that is the one that will load on the screen.
Now we will continue working on this section as we have to add our pricing options. In the Section container, we have a “Select” that needs to enter an ID so when we create our filter function we can easily call it. We will also add — onchange = “priceditems ()” which means that the onchange attribute fires the moment when the value of the element is changed.
if you have more questions about onchange you can keep looking for more information about that attribute. This will be a Function we create later on with the Filter in JavaScript.
Next would be to create four options for my filter prices. That will determine the values of my products. Beginning from the default value. which means that it will display all our products on the page.
We also need to create a grid container to add our products to our HTML portion.
Down below I have my example where you can refer to. We will also, later on, be using class="product" . Look for these class names since they would be using the JavaScript filter part.
<div class="grid-container ">
<section class="product"> <figure>
<img class="grid-img" alt="image of accessories"
src="https://images.unsplash.com/photo-1572804013427-4d7ca7268217?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1301&q=80">
</figure>
<h3></h3>
<p> After Hours // Black Smoke</p>
<p>$300.00</p>
<p><span>Type:</span> <span class="item__type">Best Selling</span></p>
<p><span class="item__price">300-400</span></p> </section> <section class="product">
<figure>
<img class="grid-img" alt="image of accessories"
src="https://d3ss0gp3e5d7m3.cloudfront.net/assets/images/desktop-womens-print-mix@2x.HhGQ7.jpg">
</figure>
<h3>QUAY EYEWEAR</h3>
<p>After Hours // Orange Tort</p>
<p>$70.00</p>
<p><span>Type:</span> <span class="item__type">Best Selling</span></p>
<p><span class="item__price">0-100</span></p>
</section> <section class="product">
<figure>
<img class="grid-img" alt="image of accessories"
src="https://d3ss0gp3e5d7m3.cloudfront.net/assets/images/desktop-kids-girls-summer-outfit@2x.1agGq.jpg">
</figure>
<h3>QUAY EYEWEAR</h3>
<p>After Hours // Shiny Black/Smoke</p>
<p>$200.99</p>
<p><span>Type:</span> <span class="item__type">Good</span></p>
<p><span class="item__price">200-300</span></p>
</section> <section class="product">
<figure>
<img class="grid-img" alt="image of accessories"
src="https://d3ss0gp3e5d7m3.cloudfront.net/assets/images/desktop-womens-outdoor-performance-wear@2x.3MU8g.jpg">
</figure>
<h3>QUAY EYEWEAR</h3>
<p>After Hours // Tort Brown/Brown Fade</p>
<p>$89.00</p>
<p><span>Type:</span> <span class="item__type">Good</span></p>
<p><span class="item__price">0-100</span></p> </section>
</div>
</main>
I will also add in here some style I added to this section. The CSS is very simple you may want to add more style. I will elaborate more on the side since it’s what makes the website look better.
.product{border: 5px solid black;box-shadow: 0 5px 5px #ccc;width: 312px;padding:10px 10px 10px 10px;}/* /////////////////////////////////////
GRID CONTAINER
///////////////////////////////////////*/
.grid-img{width: 150px; height: 200px;}.grid-container{display: grid; grid-template-columns: auto auto ; text-align: center;
padding:10px 10px 10px 100px;}/* Filter */
.item__type{display: none;
}
I hope you already have the first part we need to proceed with our Filter. Next, we will move to JavaScript. Where we will begin by building a Function. Ready to work, Here we go!!
Also, don’t forget to add <script src=”product.js”></script> At the end of your body tag.
I will like to explain some JavaScript methods that we’ll be using later on. You are free to jump this part if you know these methods.
What is Document in JavaScript?
A Document object represents the HTML document that is displayed in that window. The Document object has various properties that refer to other objects which allow access to and modification of document content. The way a document content is accessed and modified is called the Document Object Model, or DOM.
What is getElementsByClassName()?
The getElementsByClassName() a method is available on the document object and any HTML element. The getElementsByClassName() method accepts a single argument, which is a string that contains one or more class names that are being grabbed from the HTML portion.
What is getElementById()?
The Document method getElementById() returns an Element an object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.
Learn For loops
What is a For Loop?
Loops through a block of code a number of times. For this case, we need to a Loop that it will run through the options looking for the value that it’s being selected.
What is used for?
Loops are handy, if you want to run the same code over and over again, each time with a different value.
Get Anaruizrivera’s stories in your inbox
Join Medium for free to get updates from this writer.
When would we use For loops?
you should use for a loop when you know how many times the loop should run. If you want the loop to break based on a condition other than the number of times it runs, you should use a while loop.
Why do we use for Loops?
For loops, similar to while loops are used to iterate through a sequence/array of data types or objects.
Syntax
for (statement 1; statement 2; statement 3) {code block to be executed}
statement 1- Executed before the loop (the code block) starts.
statement 2 -Defines the condition for running the loop (the code block).
statement 3- Executed each time after the loop (the code block) has been executed.
EXAMPLE
for (let i = 0;statement 1i < 9; statement 2i++) {statement 3console.log(i);// more statements}for (let i = 0; i < 9; i++) {console.log(i);// more statements}
What is “.Value”?
The value property sets or returns the value of the option (the value to be sent to the server when the form is submitted).
Moving on, Now we will create a Variable that grabs in the “product” class name from HTML. Make sure you are connecting the HTML to your JavaScript page.
var items = document.getElementsByClassName(‘product’);
Now we will be creating the onchange function that we added in our Select. I will leave it here if you don’t remember.
onchange="priceItems()"Creating the function and also grabbing our “price select” class id form the HTML.
This is what we should have in our JavaScript.
I created a variable called price that is grabbing the “price select” by Id.
Moving on now we have to create a For loop function and inside the For loop, we’ll have an If and Else statement.
I will give you a brief explanation of what is an If and Else statement. Using the else if statement to specify a new condition if the first condition is false.
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
After we have created our loop that would be just saying that we want the index to start at 0. If the index is less than the length of the item, for every time that the index passes this condition we want the index to keep adding one.
// Pricevar items = document.getElementsByClassName('product');function priceItems() {var price = document.getElementById("priceSelect").value;for (var i = 0; i < items.length; i++) {var itemPrice = items[i].getElementsByClassName("item__price");var itemPriceValue = itemPrice[0].innerText;if (itemPriceValue == price) {items[i].style.display = '';}else if (price == 'default') {items[i].style.display = '';}else {items[i].style.display = 'none';}
}
}
After that we just add our condition to every If statement if the passes our condition we want the price product to be displayed on our page.
Now you are able to see your final working Filter.




