I have a basic jQuery click function to shows/hides items based on their data-filter
attribute—not using a plugin like Isotope, just a simple show/hide function— and I'd also like to apply the filter using the URL hash, when present, and append an 'active' class to the corresponding filter button.
In the markup, there is a grid of divs with the 'item' class, each of which contain anchor
elements with the relevant data-filter
, like so:
<div class="item">
<a href="#" class="item-anchor" data-filter="apples">Item</a>
</div>
In my approach below, I'm trying to get the URL hash, hide all elements whose anchors do not match the hash string, and append the active class to the matching .filter-button
element:
$(window).load(function () {
var hash = window.location.hash.substring(1);
if (hash) {
$('.item').each(function() {
$(this).children('.item-anchor').data('filter') !== hash;
}).hide();
$('a.filter-button[href="hash"]').addClass('active');
}
});
I got some assistance from this thread, but my case is a bit different. Interestingly, the code above is causing all the .item
divs to hide and the .active
class is not being appended as desired, so I'm not sure where I'm going wrong here. Any assistance is greatly appreciated, and please let me know if any further clarification is needed.
You should be invoking the filter function, instead of the each function. Additionally, you need to return the Boolean that we should filter based on. I'm not too sure what your link .active does, but I'm pretty sure you want to filter it by hash.
$(window).load(function () {
var hash = window.location.hash.substring(1);
if (hash) {
$('.item').filter(function() {
return $(this).children('.item-anchor').data('filter') !== hash;
}).hide();
$('a.filter-button[href="#'+hash+'"]').addClass('active');
}
});