Simple Content Filter

A few tweaks to http://www.sharepointdoug.com/2013/09/simple-jquery-content-filter-for-office.html

by Matthew Bramer

HTML

<div id="wrapper">
    <div id='toolbar'>
        <label>Business
            <input data-filter="business" type="checkbox" checked />
        </label>
        <label>Certification
            <input data-filter="certfication" type="checkbox" checked />
        </label>
        <label>Power User
            <input data-filter="power-user" type="checkbox" checked />
        </label>
        <label>Data &amp; BI
            <input data-filter="data-and-bi" type="checkbox" checked />
        </label>
        <label>Developer
            <input data-filter="developer" type="checkbox" checked />
        </label>
        <label>IT Pro
            <input data-filter="itpro" type="checkbox" checked />
        </label>
        <label>Cloud
            <input data-filter="cloud" type="checkbox" checked />
        </label>
        <label>Social
            <input data-filter="social" type="checkbox" checked />
        </label>
    </div>
    <div id='output'></div>
</div>

CSS

input {
    margin-left: 6px;
}
label {
    padding-right: 20px;
}
#output {
    margin-top: 20px;
    background-color: gray;
    color: #bada55;
}
#toolbar {
    background-color: white;
    position: fixed;
    top: 0;
    
}

JavaScript

/* 
    The changes to note are the <label> wrapping the input, one event is attached to the DOM and we rely on event delegation to figure out the rest, and finally one function to rule them all. :)
*/

(function ($, undefined) {
    // code here used to generate HTML.
    var categories = ["business", "certfication", "power-user", "data-and-bi", "developer", "itpro", "cloud", "social"],
        numOfFilters = categories.length - 1,
        i = 0,
        category = null,
        html = "";

    for (; i < 100; i++) {
        var random = Math.round(Math.random() * numOfFilters);
        category = categories[random];
        html += "<div data-category='" + category + "'>" + category + "</div>";
    }
    // end code to generate HTML.

    // The business end.
    $(document).ready(function () {
        var $wrapper = $("#wrapper"),
            $output = $("#output");

        $output.append(html);

        $wrapper.on("change", "input[data-filter]", function (event) {
            var $this = $(this),
                filter = $this.data("filter");

            $wrapper.find("div[data-category='" + filter + "']").slideToggle();
        });
    });


}(jQuery));