jQuery filter demo

The other night I spent a few hours hacking together an upload file control for this site. As part of that work, I decided to build a little file viewer which let me see all the images I had uploaded so far.

It turned out to be a pretty neat example of jQuery and a CSS grid layout, so I split out the filtering into a new demo: Filter demo.

Filter demo screenshot

You just type a few keystrokes and some JavaScript goes through the list of pictures and selects the ones with titles that match what you typed. Surprisingly, the JavaScript for this with jQuery is very simple:

$("#filter").keyup(function () {
    var filter = $(this).val(), count = 0;
    $(".filtered:first li").each(function () {
        if ($(this).text().search(new RegExp(filter, "i")) < 0) {
            $(this).addClass("hidden");
        } else {
            $(this).removeClass("hidden");
            count++;
        }
    });
    $("#filter-count").text(count);
});

It uses an input field with an ID of ‘filter’, a list contained in an element with class ‘filtered’, and uses the text inside each list item for filtering. The element with an ID of ‘filter-count’ has its value set to the number of elements remaining after the filter is applied.

This should be generic enough that it’s possible to apply it to many different situations. You could also modify the matching line to use the Quicksilver scoring algorithm.

The layout is completely CSS based, and should scale up and down and reflow nicely in browsers with decent CSS support. It took me quite a while to get that right, and I had to add one non-meaningful element to the markup to fix the width of each image-caption pair.

Portrait of Matt Ryall

About Matt

I’m a technology nerd, husband and father of four, living in beautiful Sydney, Australia.

My passion is building software products that make the world a better place. For the last 15 years, I’ve led product teams at Atlassian to create collaboration tools.

I'm also a startup advisor and investor, with an interest in advancing the Australian space industry. You can read more about my work on my LinkedIn profile.

To contact me, please send an email or reply on Twitter.