(Even though Wordpress is mentioned, I believe this problem is not specific to Wordpress)
I am currently building my own website using Wordpress and the theme I'm using includes the Isotope by Metafizzy package. This package helps in filtering posts on the page with clickable links.
You can view the page here
I wanted to try something similar to mypoorbrain.com, where the content on the page is filtered using URL hashes. The benefit of this is that users can navigate directly to a filtered section even from another page by entering a URL like
http://www.mypoorbrain.com/#illustration
.
After reading through the Isotope documentation, I found a section about implementing URL hashes. Below is the code snippet I tried inserting before the closing <head>
tag:
<script>
function getHashFilter() {
var hash = location.hash;
// get filter=filterName
var matches = location.hash.match(/filter=([^&]+)/i);
var hashFilter = matches && matches[1];
return hashFilter && decodeURIComponent(hashFilter);
}
$(function() {
var $grid = $('.isotope');
// bind filter button click
var $filters = $('#filters').on('click', 'button', function() {
var filterAttr = $(this).attr('data-filter');
// set filter in hash
location.hash = 'filter=' + encodeURIComponent(filterAttr);
});
var isIsotopeInit = false;
function onHashchange() {
var hashFilter = getHashFilter();
if (!hashFilter && isIsotopeInit) {
return;
}
isIsotopeInit = true;
// filter isotope
$grid.isotope({
itemSelector: '.selector col-md-6 col-lg-4',
filter: hashFilter
});
// set selected class on button
if (hashFilter) {
$filters.find('.is-checked').removeClass('is-checked');
$filters.find('[data-filter="' + hashFilter + '"]').addClass('is-checked');
}
}
$(window).on('hashchange', onHashchange);
// trigger event handler to init Isotope
onHashchange();
});
</script>
However, this code doesn't seem to be working as expected.
I suspect the issue might be related to accurately selecting the div elements (both the links and the items being sorted). Based on my observation using inspect element, it seems like the code for selecting the entire grid items is .selector col-md-6 col-lg-4'
, and the code for finding the filter buttons (or links) is
var $filterButtonGroup = $('.m-filters');
. Despite this, the filtering process still remains ineffective.
What could I be missing here? How can I ensure that the filters show up as hash links in the address bar?