Themeforest

Create An Automatic Content Filter Using jQuery & CSS Classes

The objective of today’s jQuery tutorial is to automatically generate a list of “category” links from CSS class names and use these links to filter our HTML content.

For the tutorial demo we are going to use a list of links for our jQuery tutorials, which we would like to filter by subject/category. This technique however is useful for any kind of HTML elements including; images, creating dependant select lists, unordered/ordered lists, etc and is ideal for content that needs to be listed under multiple categories or creating portfolios.

Since the actual filter list is generated dynamically we can quickly and easily add/edit/delete items that we would like to filter as well as change the categories.

View DemoDownload Source Files

HTML List

First we create our list of items to be filtered. For the purpose of the tutorial we wont include all of the list items show in the demo. On the few samples though note the class names added to each item – these are our categories/tags that we would like to use for filtering:

<ul id="demo-list">
  <li>
    <a href="/lab/jquery/demo/jquery_demo_light_weight_animated_slider.htm" class="menus animation horizontal">Lightweight Slider</a>
  </li>
  <li>
    <a href="/lab/jquery/demo/jquery_simple_horizontal_accordion.htm" class="menus animation horizontal">Simple Horizontal Accordion</a>
  </li>
  <li>
    <a href="/lab/jquery-mega-drop-down-menu-plugin/getting-started/" class="menus plugins">jQuery Mega Drop Down Menu Plugin</a>
  </li>
  <li>
    <a href="/lab/jquery/demo/jquery_animation_form_validation_errors.htm" class="forms validation ajax animation">Animated Error Messages &amp; Form Validation</a>
  </li>
  <li>
    <a href="/lab/jquery/demo/jquery_demo_image_swap_gallery.htm" class="images">Ultimate Image Swap Gallery with 3 Lines of Code</a>
  </li>
  <li>
    <a href="/lab/jquery/demo/jquery_demo_slick_jquery_captions.htm" class="images animation">jQuery Fading Image Captions</a>
  </li>
</ul>

The jQuery Code

There are basically 2 main parts to the jQuery:

Create The Filter Links – this involves retrieving all of the item classes and create a list of filter links based on the class names

A function to filter the demo list using the above links

1. Create The Filter Links

$(document).ready(function() {

// map the classes for each item into a new array
classes = $("#demo-list li a").map(function(){
    return $(this).attr("class").split(' ');
});

// create list of distinct items only
var classList = distinctList(classes);

// generate the list of filter links
var tagList = '<ul id="tag-list"></ul>';
tagItem = '<li><a href="#" class="active">all</a></li>';

// loop through the list of classes & add link
$.each(classList, function(index,value){
    var value = value.replace("-", " ");
    tagItem += '<li><a href="#">'+value+'</a></li>';
});

// add the filter links before the list of items
$("#demo-list").before($(tagList).append(tagItem));

});

// Function to create a distinct list from array
function distinctList(inputArray){
	var i;
	var length = inputArray.length;
	var outputArray = [];
	var temp = {};
	for (i = 0; i < length; i++) {
		temp[inputArray[i]] = 0;
    }
    for (i in temp) {
        outputArray.push(i);
	}
	return outputArray;
}

In the above code we first retrieve all of the class names from our list of demo links using jQuery’s map function.

This will create an array of containing all class names. In order to convert it to an array containing a distinct list of class names we pass our array to the function at the end – distinctList().

With the cleaned up output from our distinctList() function we then loop through the array and create a filter link for each item. Note that we create the complete filter links list before we insert the HTML – this will help improve performance since we only need to manipulate the DOM once.

We have also included an “all” link, which will allow us to reset the demo list filter and show all items.b

2. Filtering the Demo List

// filter the demo list when the filter links are clicked
$('#tag-list li a').live('click',function(e){

    // allows filter categories using multiple words
    var getText = $(this).text().replace(" ", "-");
    if(getText == 'all'){
        $("#demo-list li a").fadeIn();
    } else {
        $("#demo-list li a").fadeOut();
        $("#demo-list li a."+getText).fadeIn();
    }

    // add class "active" to current filter item
    $('#tag-list li a').removeClass('active');
    $(this).addClass('active');

    // prevent the page scrolling to the top of the screen
    e.preventDefault();
});

The demo list items will be filtered when the filter links are clicked. Since we create the filter links on the fly we need to use the “live” function to bind the categories.

The function allows us to use multiple words for category names by adding them as class names with hyphens – e.g. horizontal-menus would appear in the filter links as “horizontal menus”.

For this demo we will use fadeIn and fadeOut to show/hide the demo links. This can easily be substituted by any of the animation styles to suit your own tastes.

Finally at the end of our click function we add code to give the current filter item the class “active” and use e.preventDefault() to stop the browser scrolling to the top of the screen when the filter links are clicked.

The Complete jQuery Code

The complete jQuery code for our automatic content filter is:

$(document).ready(function() {

// map the classes for each item into a new array
classes = $("#demo-list li a").map(function(){
    return $(this).attr("class").split(' ');
});

// create list of distinct items only
var classList = distinctList(classes);

// generate the list of filter links
var tagList = '<ul id="tag-list"></ul>';
tagItem = '<li><a href="#" class="active">all</a></li>';

// loop through the list of classes & add link
$.each(classList, function(index,value){
    var value = value.replace("-", " ");
    tagItem += '<li><a href="#">'+value+'</a></li>';
});

// add the filter links before the list of items
$("#demo-list").before($(tagList).append(tagItem));

// filter the demo list when the filter links are clicked
$('#tag-list li a').live('click',function(e){

    // allows filter categories using multiple words
    var getText = $(this).text().replace(" ", "-");
    if(getText == 'all'){
        $("#demo-list li a").fadeIn();
    } else {
        $("#demo-list li a").fadeOut();
        $("#demo-list li a."+getText).fadeIn();
    }

    // add class "active" to current filter item
    $('#tag-list li a').removeClass('active');
    $(this).addClass('active');

    // prevent the page scrolling to the top of the screen
    e.preventDefault();
});
});

// Function to create a distinct list from array
function distinctList(inputArray){
	var i;
	var length = inputArray.length;
	var outputArray = [];
	var temp = {};
	for (i = 0; i < length; i++) {
		temp[inputArray[i]] = 0;
    }
    for (i in temp) {
        outputArray.push(i);
	}
	return outputArray;
}

View DemoDownload Source Files

10 Comments

  • Good day to you. Can I make a double filter for example, not only on the “class”, but also on the “rel”.
    An example of the life. Vehicle brand and country of manufacturer. In principle, countries can limit the list of products from 10 countries.
    Something like that shown here http://razorjack.net/quicksand/
    Only when a filter is used on the grounds, plus sorting, and need two filters.
    P.S. I’m sorry for my english, thanks to google for help.

    • yes should be able to no problem

  • categories consisting of 2 words the script splits and generates 2 lists

  • sorry, wordpress cuts comments
    the link to waht my php/html looks like is
    http://dl.dropbox.com/u/2153133/wp_posts_filter.txt

    • Then you need to change the jquery to:

      $(document).ready(function() {
      
      // map the classes for each item into a new array
      classes = $("#demo-list li").map(function(){
          return $(this).attr("class").split(' ');
      });
      
      // create list of distinct items only
      var classList = distinctList(classes);
      
      // generate the list of filter links
      var tagList = '<ul id="tag-list"></ul>';
      tagItem = '<li><a href="#" class="active">all</a></li>';
      
      // loop through the list of classes & add link
      $.each(classList, function(index,value){
          var value = value.replace("-", " ");
          tagItem += '<li><a href="#">'+value+'</a></li>';
      });
      
      // add the filter links before the list of items
      $("#demo-list").before($(tagList).append(tagItem));
      
      // filter the demo list when the filter links are clicked
      $('#tag-list li a').live('click',function(e){
      
          // allows filter categories using multiple words
          var getText = $(this).text().replace(" ", "-");
          if(getText == 'all'){
              $("#demo-list li").fadeIn();
          } else {
              $("#demo-list li").fadeOut();
              $("#demo-list li."+getText).fadeIn();
          }
      
          // add class "active" to current filter item
          $('#tag-list li a').removeClass('active');
          $(this).addClass('active');
      
          // prevent the page scrolling to the top of the screen
          e.preventDefault();
      });
      
      });
      
      // Function to create a distinct list from array
      function distinctList(inputArray){
          var i;
          var length = inputArray.length;
          var outputArray = [];
          var temp = {};
          for (i = 0; i < length; i++) {
              temp[inputArray[i]] = 0;
          }
          for (i in temp) {
              outputArray.push(i);
          }
          return outputArray;
      }
      
  • hi i’trying to implement this in wordpress
    the <ul id="tag-list doesn't show or doesn't appear automatically
    please help

    • Hi,
      Make sure that the ID of your wordpress list is either #demo-list or that actual ID is used in the jQuery code

      • post_content, ‘bones-frontthumb-170′);
        if ($thumb!=”) { ?>
        <li class="
        category_nicename;
        ?>
        “><a href="” title=”" rel=”postthumb”><img class="alignleft" src="” alt=”" />

        —–
        renders html:


        ……..
        and several more li’s

        • Hi,

          The above code wont work with the jquery given in the tutorial. The class names should be on the a tag.

  • sweet. thank you.