jQuery Isotope – Filtering Results for URL

This one may well help somebody out. Working on the Face Group wordpress site at the moment and I’m using Isotope, a jQuery plugin designed to create magical layouts. It’s the big brother of Masonry, an excellent bit of work by David DeSandro at Metafizzy.

The Filtering function is fantastic, it allows you to give the user the ability to filter and reload the layout dynamically, using tags or a defined list. In the case of the Face site, I wrote a custom WordPress query which mimics wp_list_categories and loads in the category list and creates the nav menu to work with the Isotope filtering instructions here. Trouble is that only works when you’re already on the page with all the portfolio items on it, if you are coming at it from one of the other WordPress pages then you won’t see the filtered list.

The solution? We pass the filter id across via a cookie using the jQuery Cookie plugin. Our header.php file generates two different navigation lists depending which page the user is on (and changes the id of the unordered list appropriately;

<?php

if (is_front_page()) {
   $homelink = '#';
   echo '<ul id="filters">';
} else {
   $homelink =  get_bloginfo('url').'/';
   echo '<ul id="cookiefilter">';
}

?>

Then the Javascript was changed so that if the link being clicked was part of cookiefilter menu (ie off the Isotope page) then the #cookiefilter a click event was fired and a cookie created. The code block below that filters Isotope based on the cookie and then destroys it. The site it’s on is;

http://www.face-educationmarketing.co.uk

To see it in action an explanation. The home page has Isotope on it and all the entries underneath the ‘Work’ header are Isotope filters. The ‘About’ header is a WP menu, click on one of those links under ‘About’ and you are taken to different WP page. Now examine the change in the markup on the Work filter list – the ul class has changed, it is now;

<ul class="cookiefilter">

rather than;

<ul class="filters">

This is the important bit because in the JS below, a click event on #filters a behaves differently to click events on #cookiefilter a

In the latter case a cookie is created with the cookie name in it. The onload JS checks to see if such a cookie exists, if it does then it calls Isotope, filters it with the value in the cookie and then destroys the cookie so the normal filters then work. Here’s the JS;

		// filter items when filter link is clicked
		$('#filters a').click(function(){
			var selector = $(this).attr('data-filter');
			$container.isotope({ filter: selector });
			return false;
		});

		// Set cookie based on filter selector
		$('#cookiefilter a').click(function(){
			var selector = $(this).attr('data-filter');
			$.cookie("listfilter", selector, { path: '/' });
		});
		
		if ( $.cookie("listfilter") ) {
			$container.isotope({ filter: $.cookie("listfilter") });
			$.cookie("listfilter", null, { path: '/' });
			return false;
		}