JavaScript Filter Gallery Example

Go back to JavaScript Index

In this tutorial, we will be creating a gallery with a filtering option, like the one shown here:

The Gallery

unsplash-logoJordan Arnold unsplash-logoVincent van Zalinge

The code

The HTML

<h2>The Gallery</h2>

<button id="all" class="active">All</button>
<button id="nature">Nature</button>
<button id="animals">Animals</button>

<div class="gallery">
<!-- image by Jordan Arnold -->
<img src="img/img1.jpg" alt="Nature" class="filter all nature">
<!-- images by Vincent van Zalinge -->
<img src="img/img2.jpg" alt="Fawn" class="filter all animals">
<img src="img/img3.jpg" alt="Butterfly" class="filter all animals">
<img src="img/img4.jpg" alt="Hare" class="filter all animals">
</div>
1.0 | The HTML

The CSS

.gallery {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-gap: 10px;
}
.active {
background-color: #F9819F;
}
1.1 | The CSS

The JS

// Declaring a variable that stores an array of all elements with class name filter
const imgs = Array.from(document.getElementsByClassName("filter"));

// Declaring a variable that stores an array of all button elements
const buttons = Array.from(document.getElementsByTagName("button"));

// Declaring a function using the arrow syntax that 1) iterates through the array of buttons removing the class attribute, 2) adds the class active to the source element that triggered the function and 3) calls the filterFunc function, passing the id of the element that triggered the function as argument.
const btnClicked = (e) => {
buttons.forEach(button => {
button.removeAttribute("class");
})
e.srcElement.classList.add("active");
filterFunc(e.srcElement.id);
}

// Declaring a function using the arrow syntax that 1) iterates through the array of elements with class name filter and when doing so changes the value of the display property to none, 2) declares a new variable that stores an array of the elements from the imgs variable, whos class list include the value matching the id of the element clicked, and 3) makes the elements contained in the new array display grid.
const filterFunc = (category) => {
imgs.forEach((img) => {
img.style.display = "none";
})

let filter = imgs.filter((img) => {
return img.classList.value.includes(category);
})

filter.forEach((img) => {
img.style.display = "grid";
})
}

// Iterating through the array of buttons, adding an event listener to each of them that calls the btnClicked function.
buttons.forEach(button => {
button.addEventListener("click", btnClicked);
})
1.2 | The JavaScript