Building a Checkbox Filter With Vanilla JavaScript
By: Christopher Clemmons
Tags: Array Methods, Javascript Development, Javascript Tips, Front End Development, Software Development

Photo by Wade Austin Ellis on Unsplash

I have been looking all over the internet just for a simple feature that is so common but I have yet to find an article that teaches you how to build this system in plain English.

“When I do things myself, it’s done correctly.”

The above quote is a phrase I commonly say to myself when dealing with issues or building custom features for my websites and applications.

So what exactly will we be coding today?

This small project we’re building today will allow the user to pedantically filter the requested products based on the query created from the currently checked check-boxes. It will also display a subtle animation with the help of the Animate-On-Scroll library from here.

Makes sense?

Here is a better idea, check out this link to see a live demo of what I am talking about.

Now that you get the idea, lets get started with building this out. I strongly recommend having the basic knowledge of HTML, CSS/SCSS and JavaScript to build this.

Step 1: HTML

For the HTML, well will build 2 modules. The first one will be the wrapper that contains all the check-boxes and the second will be a div that will hold all the cards.

Before adding the main HTML, lets add our dependencies. Since we will be using the AOS library, lets include the CDN links to our head.

Head

Awesome, now that you have that, you can added the wrapper and the checkboxes. Styling is completely discretional but you are more than welcome to use the styling in the CSS section.

HTML (check-box & card container)

Next, add the div that will contain all of your check-boxes and the one that will hold your cards. Add as many checkboxes you like while giving it the neccessary values and attrbutes.

<div id="filter-input-wrapper">

<input value="value" type="checkbox" id="your-id"name="value" />

</div> <div id="wrapper"></div>

Step 2: CSS (optional)

I would highly recommend adding the CSS from my project if you’re trying to code along exactly. Again, this is purely at your descretion. Any css will work since it wont affect the function of this program.

* {

padding: 0;

margin: 0;

box-sizing: border-box;

} html {

font-size: 14px;

} body {

} #filter-input-wrapper {

background: rgb(228, 228, 228);

padding: 2rem 0;

display: flex;

justify-content: center;

.input-block {

padding: 10px;

input[type="checkbox"] {

-ms-transform: scale(1.3);

-moz-transform: scale(1.3);

-webkit-transform: scale(1.3);

-o-transform: scale(1.3);

transform: scale(1.3);

padding: 10px;

}

label {

font-size: 1.2rem;

}

}

}

In order to use SCSS, install a SASS watcher to your code editor. Here is a video I would recommend to get started.

Step 3: JavaScript

I will be breaking up the javascript into sections to ensure you get the full understanding of how this will all be pieced together.

Creating the Data Array.

const data = [ {title:’Name’, classes:[‘category1',’category2']}]

The title will be used on the actual cards to help you see what is being filterd in real time on the DOM. The classes array will be accessed and compared to an array of the values from the check-boxes that are currently checked.

Variable Declaration

Let’s now grab all the check-boxes and the card wrapper div.

const checkboxes = document.querySelectorAll("input[type='checkbox']"); const cardContainer = document.getElementById("wrapper");

Next, we will create an array that will hold the values of the currently checked check-boxes. This will also be updated everytime there is a change event to any of the check-boxes.

var checkboxValues = [ ];

Functions

The first function we will build is the populateCards function. This will take all the objects in the data array that we created earlier, loop thru them all to get the details we need to create the cards and add them to the wrapper automatically.

function populateCards() {

var time = 100;



data.forEach((obj) => {

var card = `

<div data-aos="fade-up" data-aos-duration=${time} class="card"><h1 class="title">${obj.title}</h1></div>

`; time += 50;

wrapper.innerHTML += card;

});

} populateCards()

Add an change event to each check-box.

checkboxes.forEach((box) => {

box.checked = false;

box.addEventListener("change", () => filterCards());

});

The data-aos and data-aos-duration will control our animations. Check out the documentation here to see all of the different animation options that are available fo use.

The time integer is a mutable variable that will be changed after each card is added to the wrapper div. Time will set how long each animation will take to complete. 50ms will be added to time after each card has been created. This creates a staggering effect to the cards as they load.

Our next function will loop throught all of the check-boxes and return an array that contains its values. This will be used to compare the “classes” array from each item in the data array to the newly returned array from this function.

function grabCheckboxValues() {

var checkboxValues = [];

checkboxes.forEach((checkbox) => {

if (checkbox.checked) checkboxValues.push(checkbox.value);

});

return checkboxValues;

}

All that this function is doing is looping though every check-box that is checked and adding the value to the checkboxValues array. Then, that array is returned and can be used in any part of our program that runs “grabCheckboxValues()”.

Our last function “filterCards()” will do exactly what it says, filte the cards. As you notice the line with wrapper.innerHTML = “”, all this is doing is making sure that there are no cards in the div as it repopulates it with the filtered cards. This prevents duplicating the content.

function filterCards() {

wrapper.innerHTML = "";

checkboxValues = grabCheckboxValues(); data.forEach((item) => {

let classes = item.classes;

let result = (arr, target) => target.every((v) => arr.includes(v)); let isMatch = result(classes, checkboxValues);

if (isMatch) {

var card = `

<div data-aos="flip-down" data-aos-duration=500 class="card" style="padding:10px; min-width:400px; background-color:#CCC; margin:10px;">

<h1 class="title">${item.title}</h1>

</div>

`;

wrapper.innerHTML += card;

}

});

}

The checkboxValues variable takes in a new value from the returned array from “grabCheckboxValues()”.

While the data array is being looped, it is creating explicit variable that will contain all the elements in the “classes” array for each item in the data array. The result variable will check to see if each item.classes array contains at least all of the items in the checkboxValues array, and the isMatch holds the boolean created from the result function.

If the item.classes array contains at least all of the items in the checkboxValues arrau, that card gets added to the DOM along with the others (if applicable) that meets this criteria.

Conclusion.

Front end engineering can be tricky at times, even for me since the resources used for building apps and websites are always changing. This is why I love creating these articles so I can learn while teaching, and teach while learning.

Feel free to read my other articles to learn more coding cocepts to improve your skillset as a developer.