Recreating the Photo Gallery Filter Using jQuery, Part 2
Master advanced jQuery filtering with JavaScript arrays
This is Part 2 of the photo gallery filter series. Complete Part 1 first to understand the foundation concepts and button functionality.
Key Learning Objectives
Array Population
Learn to populate JavaScript arrays using jQuery methods and handle data-filter attributes efficiently.
Filter Logic
Implement both inclusive and exclusive filtering systems with checkbox toggle functionality.
DOM Manipulation
Master jQuery methods for showing, hiding, and selecting elements based on dynamic criteria.
Setup Process
Close Existing Files
Close any currently open files in your code editor to start fresh.
Navigate to Project Folder
Go to Desktop > Class Files > yourname-JavaScript jQuery Class and open Photo-Filter-jQuery-2 folder.
Open Required Files
Open both gallery-with-jQuery.html for editing and gallery-with-js.html as reference.
jQuery vs Standard JavaScript Loops
| Feature | Standard JavaScript | jQuery Approach |
|---|---|---|
| Syntax Complexity | for(i=0; i<array.length; i++) | $.each(array, function(i)) |
| Readability | More verbose | Cleaner and intuitive |
| Error Handling | Manual bounds checking | Built-in safety |
The shift() method removes the first array element and shifts remaining elements down by one index. This is perfect for removing the 'all' filter from our selection array.
The shift() method deletes the first item in the Array and shifts the other values so that 1 becomes 0, 2 becomes 1, etc.
Filter Selection Logic
Use data-selected attribute to determine button state
Use jQuery.each() to iterate through all filter buttons
Only add filters with data-selected='yes' to selectedArray
Verify array population by logging results to browser console
Hide Methods Comparison
| Feature | jQuery hide() | jQuery css() |
|---|---|---|
| Code Syntax | $imageContainers.hide() | $imageContainers.css('display', 'none') |
| Readability | Highly readable | More explicit |
| Functionality | Sets display: none | Sets display: none |
The :checked pseudo-class works similarly to :hover. Use $exclusive.is(':checked') to test checkbox state in jQuery.
selectedArray.each() won't work because selectedArray is not a jQuery object. Use $.each(selectedArray, function(i){}) instead to iterate over standard JavaScript arrays.
Inclusive Filter Implementation
Use $.each() Method
Apply jQuery.each() to non-jQuery arrays by passing array as first argument
Build Class Selector
Concatenate '.' with selectedArray values to create valid CSS class selectors
Show Matching Elements
Use jQuery show() method to display elements matching the constructed selector
Exclusive vs Inclusive Filtering
Key Takeaways
