Filtering multiple categories using data-category attribute in jQuery

I am trying to build a filtering component with CSS animations and jQuery by the help of Filtering Component. I did everything perfectly following the article. However, I was trying to make the filtering for multiple categories. Say, there are more than one categories and the HTML markup is like below:

<a class="red" data-category="red, green, blue" href="#">Box1</a>

In this case how to code the jQuery to filter the above html code where data-category has more than one categories. I am not good in jQuery. Will be a great help for me if someone do this for me. The jQuery code is:

(function($) {

  'use strict';

  var $filters = $('.filter [data-filter]'),
    $boxes = $('.boxes [data-category]');

  $filters.on('click', function(e) {
    e.preventDefault();
    var $this = $(this);

    $filters.removeClass('active');
    $this.addClass('active');

    var $filterColor = $this.attr('data-filter');

    if ($filterColor === 'all') {
      $boxes.removeClass('is-animated')
        .fadeOut().promise().done(function() {
          $boxes.addClass('is-animated').fadeIn();
        });
    } else {
      $boxes.removeClass('is-animated')
        .fadeOut().promise().done(function() {
          $boxes.filter('[data-category = "' + $filterColor + '"]')
            .addClass('is-animated').fadeIn();
        });
    }
  });

})(jQuery);

Any help would be greatly appreciated. Thanks.

OK, I got the answer for my query. I have to assign *= in the above jQuery like below:

$boxes.filter(’[data-category *= “’ + $filterColor + '”]’)
.addClass(‘is-animated’).fadeIn();

This works like a charm!

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.