Category Filtering with Isotope in Jekyll

September 15, 2016
Category: Projects
Tags: Jekyll

This is the most recent addition to my Jekyll Tools repository on GitHub. Isotope is a popular jQuery filtering and sorting plugin. I combined it with Liquid to generate category filtering in Jekyll.

You can see it in action at http://cagrimmett.com/category-isotope/.

You can find the code for this in my Jekyll Tools repo on GitHub.

This works by using YAML front matter to set categories and then outputting those categories as buttons and class names to work with the Isotope plugin.

Generate the buttons from categories:

<div class="button-group filter-button-group">
	{% for category in site.categories %}
		<a class="button" data-filter=".{{ category | first }}">{{ category | first }}</a>
	{% endfor %}
		<a class="button active" data-filter="*">All</a>
</div> 

Generate your posts:

 <div class="grid">
	{% for post in site.posts %}
     <div class="element-item {{ post.category }}">
        <span class="post-meta">{{ post.date | date: "%b %-d, %Y" }}</span>

        <h2>
          <a class="post-link" href="{{ post.url | prepend: site.baseurl }}">{{ post.title }}</a>
        </h2>

        <p>
          {{ post.excerpt }}
        </p>
     </div>
    {% endfor %}
</div> 

“All” is selected by default. The other buttons come from the category you specify at the top of a post in your YAML front matter.

Include the jQuery and Isotope libraries, then set up the functions to trigger the filtering and setting an “active” class on your buttons so you can highlight the active one:

<script src="http://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<script src="https://unpkg.com/isotope-layout@3.0/dist/isotope.pkgd.js"></script>
// init Isotope
var $grid = $('.grid').isotope({
  // options
});
// filter items on button click
$('.filter-button-group').on( 'click', 'a', function() {
  var filterValue = $(this).attr('data-filter');
  $grid.isotope({ filter: filterValue });
});
$('.button-group a.button').on('click', function(){
	$('.button-group a.button').removeClass('active');
	$(this).addClass('active');
});

Find this post useful?

Buy me a coffeeBuy me a coffee