[Solved] JQuery Filter Gallery: Combine Two Filters? [closed]


Firstly, here’s a new working CodePen.

What I have done is to use variables, category and day to persist the chosen category and day filter values respectively. This is instead of relying on the existence of a .selected class appearing on each filter element.

This has the benefit of firstly removing the need for the .selected classes all together, and secondly it means that your UI state isn’t being persisted in the DOM itself.

I have also removed all of your code for adding and removing the .ACTIVE and .PASSIVE classes, and instead combined this with the filter click event listeners. It avoids the repetition and keeps everything much neater.

Finally, I’ve added copious comments to hopefully explain what is happening at each step so that you can learn how it works.

If you have any questions, ask.

// Prepare cards, filters, and no results message
var $cards = $('.class-card');
var $dayFilters = $('.dayFilter');
var $categoryFilters = $('.categoryFilter');
var $noResults = $('#noResults');

// Initialise by calling filter cards
filterCards();

// Prepare selected category and day filter values
var category = null;
var day = null;

// Bind click event to set selected category filter
$categoryFilters.on('click', function (e) {
  // Get clicked category filter
  var $category = $(e.target);

  // Deselect all categories, and select clicked category
  $categoryFilters.addClass('PASSIVE').removeClass('ACTIVE');
  $category.addClass('ACTIVE').removeClass('PASSIVE');

  // Record clicked category filter value
  category = $category.data('target');

  filterCards();
});

// Bind click event to set selected day filter
$dayFilters.on('click', function (e) {
  // Get clicked day filter
  var $day = $(e.target);

  // Deselect all days, and select clicked day
  $dayFilters.addClass('PASSIVE').removeClass('ACTIVE');
  $day.addClass('ACTIVE').removeClass('PASSIVE');

  // Record clicked day filter value
  day = $day.data('target');

  filterCards();
});

function filterCards() {
  // Show all cards and hide no results message
  $cards.show();
  $noResults.hide();

  // Reset filter classes
  var filters = [];

  // Add category and day filter classes, where selected
  if (category) filters.push('.' + category);
  if (day) filters.push('.' + day);

  // Filter cards where one or more filters selected
  if (filters.length) {
    // Hide cards that do not match filters
    $cards.not(filters.join('')).hide();

    // Show no results message if no cards are visible
    if ($cards.has(':visible').length === 0) $noResults.show();
  }
}

solved JQuery Filter Gallery: Combine Two Filters? [closed]