CSS list filter and view

The goal of this fiddle was to provide a CSS and JavaScript method to switch between a list and card or grid view.

It uses jQuery and a very simple filter that fires on keyup.

The code is commented here, you can see it run at http://jsfiddle.net/PbCV3/5/


$(document).ready(function () {

    $("#filter").keyup(function () {
        var filter = $(this).val().toLowerCase();
        var len = filter.length;
        $("li").each(function () {
            /* You may want to use indexOf instead of substring to filter */ 
            if ($(this).html().substring(0, len).toLowerCase() != filter) {
                $(this).addClass('hidden');
            } else {
                $(this).removeClass('hidden');
            }
        });
        /* Check if the list is in card view or list view */
        if ($("ul").hasClass("cards")) {
            cards();
        } else {
            list();
        }
    });
    $("#controls").delegate("button", "click", function () {
        /* The id of the button clicked corresponds to the class of the list */
        var id = $(this).attr("id");
        $("ul").removeClass();
        $("ul").addClass(id);
        if (id == "cards") {
            cards();
        } else {
            list();
        }
    });

    function cards() {
        var count = 0,
            adjacent, adjHeight, thisHeight, newHeight;
        /* The visible pseudo class is a jQuery extension */
        $("li:visible").each(function () {
            /* adjacent is the item of the list which is on the same row */
            adjacent = (count % 2) ? $(this).prev("li:visible") : $(this).next("li:visible");
            if (adjacent) {
                adjHeight = $(adjacent).height();
                thisHeight = $(this).height();
                /* The new height should be the height of the taller item */ 
                newHeight = Math.max(adjHeight, thisHeight);
                if (newHeight == thisHeight) {
                    $(adjacent).height(newHeight);
                } else {
                    $(this).height(newHeight);
                }
            }
            /* count is used to determine whether the item is on the left or right */
            count++;
        });
    }

    function list() {
        /* Restore the heights to auto */
        $("li").each(function () {
            $(this).height("auto");
        });
    }

});