How to filter multiple categories with jQuery

728 Views Asked by At

I am trying to build a filtering component with CSS animations and jQuery by the help of this article. 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);

Thanks

1

There are 1 best solutions below

0
Md Iftekharul On

After studying on Java Assignment Operators I got a solution for my query. In the above jQuery code just add *= in the below line:

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

This works like a charm!