Advertisement

Quick and Easy Filtering with jQuery

by
Student iconAre you a student? Get a yearly Tuts+ subscription for $45 →

In this week's screencast, we'll learn how to implement quick and dirty filtering without a database. By applying some classes and a touch of jQuery, we can implement a nice little system very quickly.


Overview

Just yesterday, I was asked how I was able to create the simple sorting feature found on the Vault page of my blog. Truthfully, it was done out of haste. Though I'll eventually run everything through a database and sort it that way, for now, I needed a quick and dirty way to do it with JavaScript. I'll show you what I did.

20 Minute Video Tutorial

Other Viewing Options

The Final jQuery

Updated a bit from the video.

var ulOptions = '
'; var $links = $('#links'); $links.before(ulOptions) .children('li') .addClass('all') .filter('li:odd') .addClass('odd'); $('#options li a').click(function() { var $this = $(this), type = $this.attr('class'); $links.children('li') .removeClass('odd') .hide() .filter('.' + type) .show() .filter(':odd') .addClass('odd'); return false; });

Update: Sneaky Little Bug

"SFdude" found a bug where, if you click on the same item twice, the entire list will disappear! Luckily, I was able to determine the problem quickly. The issue was that after the first click, we applied a class of "selected" to the anchor tag. That is what was causing the hiccup. Because now - it had two classes that would not correspond to anything! The fix is to remove these two lines:

$('#options li a').removeClass('selected');
$this.addClass('selected');

Truthfully - they were unnecessary. We can just as easily use the a:focus selector in our stylesheet to accomplish this. :)

a:focus {
 font-weight: bold;
}

And that does it. I've updated the demo and the source code. Thanks to SFdude for finding that sneaky little bug.

So what are your thoughts? Disagree with this method? Is there a better way to do it - without a database? Let me know!

Thank you, Screencast.com!


Screencast.com
...for providing the hosting for these video tutorials.