Table of Contents
Creating a dynamic photo gallery enhances user experience by allowing visitors to filter and sort images based on categories or preferences. Using JavaScript, developers can build interactive galleries that update instantly without needing to reload the page. This article guides you through the process of creating such a gallery with filters and sorting options.
Setting Up the HTML Structure
Begin by creating the basic HTML layout. You will need a container for your images, filter buttons, and sorting options. Use data attributes to categorize images for easy filtering.
Here is an example structure:
<div id="filter-buttons">
<button data-filter="all">Show All</button>
<button data-filter="nature">Nature</button>
<button data-filter="city">City</button>
</div>
<div id="sort-options">
<button data-sort="name">Sort by Name</button>
<button data-sort="date">Sort by Date</button>
</div>
<div id="gallery">
<div class="photo" data-category="nature" data-name="Sunset" data-date="2023-06-15"><img src="sunset.jpg" alt="Sunset"></div>
<div class="photo" data-category="city" data-name="Skyscraper" data-date="2023-07-01"><img src="skyscraper.jpg" alt="Skyscraper"></div>
Repeat for additional images, assigning appropriate data-category, data-name, and data-date attributes.
Adding JavaScript for Filtering and Sorting
Next, include JavaScript to handle filtering and sorting. This script will listen for button clicks and update the gallery accordingly.
Example script:
const filterButtons = document.querySelectorAll('#filter-buttons button');
const sortButtons = document.querySelectorAll('#sort-options button');
const gallery = document.getElementById('gallery');
let photos = Array.from(gallery.children);
filterButtons.forEach(button => {
button.addEventListener('click', () => {
const filter = button.getAttribute('data-filter');
photos.forEach(photo => {
if (filter === 'all' || photo.getAttribute('data-category') === filter) {
photo.style.display = '';
} else {
photo.style.display = 'none';
}
});
});
Similarly, add event listeners for sorting buttons to reorder photos based on data attributes like name or date.
Conclusion
By combining HTML, CSS, and JavaScript, you can create a flexible and interactive photo gallery. Filters and sorting options improve navigation, helping users find images quickly. Experiment with different styles and functionalities to customize your gallery further.