Create Basic Product Filters using jQuery

Create Basic Product Filters using jQuery
File Size: 85.4 KB
Views Total: 11755
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

A basic jQuery implementation of product filters that allow you to filter html elements inside a container using Html5 data-* attributes.

Basic usage:

1. Load the necessary jQuery JavaScript library in the html page.

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>

2. Create a list of products and group them using data-* attributes.

<div class="sections">
  <ul>
    <li class="grid-products" data-colour="red"><span>Product 1</span></li>
    <li class="grid-products" data-colour="yellow"><span>Product 2</span></li>
    <li class="grid-products" data-colour="green"><span>Product 3</span></li>
    <li class="grid-products" data-colour="red"><span>Product 4</span></li>
    <li class="grid-products" data-colour="blue"><span>Product 5</span></li>
  </ul>
</div>

3. Create checkbox based product filters.

<div id="filters" class="sections">
  <div>
    <h4>Colour</h4>
    <input type="checkbox" name="colour" id="red" value="red" >Red</input>
    <input type="checkbox" name="colour" id="blue" value="blue">Blue</input>
    <input type="checkbox" name="colour" id="green" value="green">Green</input>
    <input type="checkbox" name="colour" id="yellow" value="yellow">Yellow</input>
  </div>
  <div>
    <input type="button" id="none" value="Clear all"></input>
  </div>
</div>

5. The core JavaScript to enable the product filters.

$(document).ready(function() {
  var $products = $('.grid-products'),
      $filters = $("#filters input[type='checkbox']"),
      product_filter = new ProductFilterLevel1($products, $filters);
  product_filter.init();
});

function ProductFilterLevel1(products, filters) {
  var _this = this;

  this.init = function() {
    this.products = products;
    this.filters = filters;
    this.bindEvents();
  };

  this.bindEvents = function() {
    this.filters.click(this.filterGridProducts);
    $('#none').click(this.removeAllFilters);
  };

  this.filterGridProducts = function() {
    _this.products.hide();
    var selectedFilters = _this.filters.filter(':checked');
    if (selectedFilters.length) {
      var selectedFiltersValues = [];
      selectedFilters.each(function() {
        var currentFilter = $(this);
        selectedFiltersValues.push("[data-" + currentFilter.attr('name') + "='" + currentFilter.val() + "']");
      });
      _this.products.filter(selectedFiltersValues.join(',')).show();
    } else {
      _this.products.show();
    }
  };

  this.removeAllFilters = function() {
    _this.filters.prop('checked', false);
    _this.products.show();
  }
}

This awesome jQuery plugin is developed by yuktikhurana. For more Advanced Usages, please check the demo page or visit the official website.