Categories: CSSScriptWeb Design

Filter & Sort DOM Elements with Advanced Filter System

Advanced Filter System (AFS) is a JavaScript library that helps you easily add filtering, searching, and sorting to your websites.

The library is designed to create dynamic filtering interfaces for content organization. Users can filter your content based on multiple criteria such as categories, price ranges, date ranges, ratings, tags, search text, and more.

AFS is useful for any website displaying collections of items, such as product catalogs, image galleries, or blog post listings. It even manages URL states so users can share filtered results.

How
Sponsored
to use it:

1. Install the library via NPM or download the ZIP file from our website.

# NPM
$ npm install advanced-filter-system
<script src="/dist/afs.min.js"></script>
<link rel="stylesheet" href="/dist/afs.min.css">

2. Categorize your filterable content using the data-categories attribute. You can assign multiple filter criteria to each item by separating them with spaces. For example:

<div class="product-grid">
  <div class="filter-item" 
    data-categories="category:tech price:low" 
    data-title="Smartphone"
    data-description="Custom Description"
    data-price="19.99">
    <!-- Product content -->
  </div>
  <div class="filter-item" 
    data-categories="category:tech" 
    data-price="medium" 
    data-title="Laptop Ultra">
    <!-- Product content -->
  </div>
  <div class="filter-item" 
    data-categories="category:fashion" 
    data-price="low" 
    data-title="Designer Jeans">
    <!-- Product content -->
  </div>
  ...
</div>

3. Create buttons for users to select different filters. Assign the filter values to the data-filter attribute.

<div class="filters">
  <button class="btn-filter" data-filter="*">All</button>
  <button class="btn-filter" data-filter="category:tech">Tech</button>
  <button class="btn-filter" data-filter="category:fashion">Fashion</button>
</div>

4. If you want to provide a search option, add an input box with a class of filter-search.

<input type="text" class="filter-search" placeholder="Search...">

5. To display how many items match the current filter, add a filter-counter element.

<div class="filter-counter"></div>

6. Create a container to hold the pagination links.

<div class="pagination-container"></div>

7. Initialize the Advanced Filter System with the desired options:

  • containerSelector: The main container that holds the items to be filtered.
  • itemSelector: The class of each item to filter.
  • filterButtonSelector: The filter buttons to toggle filtering.
  • searchInputSelector: The input field for search.
  • counterSelector: Displays the number of matched items.
  • activeClass: Class applied to active filters.
  • hiddenClass: Class used to hide non-matching items.
  • animationDuration: Animation speed in milliseconds.
  • AnimationType: ‘fade’, ‘slide’, ‘scale’, etc.
  • filterMode: Defines how filters are combined (“OR” or “AND”).
  • searchKeys: List of data attributes to search through.
  • debounceTime: Delay for the search input to prevent unnecessary filtering.
  • debug: Enable console logs
  • logLevel: ‘info’, ‘warn’, ‘error’, ‘debug’
const afs = AFS.createAFS({
      containerSelector: ".filter-container",
      itemSelector: ".filter-item",
      filterButtonSelector: ".btn-filter",
      searchInputSelector: ".filter-search",
      counterSelector: ".filter-counter",
      activeClass: "active",
      hiddenClass: "hidden",
      animationDuration: 300,
      animationType: 'fade',
      animationEasing: 'ease-out',
      filterMode: "OR",
      searchKeys: ["title"],
      debounceTime: 300,
      debug: false, // Enable console logs
      logLevel: 'info', // 'info', 'warn', 'error', 'debug'
      dateFormat: 'YYYY-MM-DD',
      counter: {
        template: 'Showing {visible} of {total}',
        showFiltered: true,
        filteredTemplate: '({filtered} filtered)',
        noResultsTemplate: 'No items found',
        formatter: (num) => num.toLocaleString()
      },
      styles: {
        slider: {
          class: 'afs-range-slider',
          trackClass: 'afs-range-track',
          thumbClass: 'afs-range-thumb',
          valueClass: 'afs-range-value',
          selectedClass: 'afs-range-selected',
          ui: {
            showHistogram: false,
            bins: 10 // Number of bins for histogram
          }
        },
        colors: {
          primary: '#000',
          background: '#e5e7eb',
          text: '#000',
          histogram: '#e5e7eb', 
          histogramActive: '#000' 
        }
      },
      // Pagination options
      pagination: {
        enabled: false,
        itemsPerPage: 10,
        container: '.afs-pagination-container',
        pageButtonClass: 'afs-page-button',
        activePageClass: 'afs-page-active',
        containerClass: 'afs-pagination',
        scrollToTop: false,
        scrollOffset: 50,
        scrollBehavior: 'smooth', // or 'auto' for instant scroll
      }
});

7. Available API methods.

// Add filters
afs.filter.addFilter('category', 'tech');
afs.filter.addFilter('price', 'low');

// Remove filters
afs.filter.removeFilter('category', 'tech');

// Clear all filters
afs.filter.clearAllFilters();

// Alternative method
afs.filter.setLogic('AND');
afs.filter.setLogic(true); // true = AND, false = OR
// OR
afs.filter.setFilterMode('AND'); 
afs.filter.setFilterMode('OR');

// Get active filters by type
afs.const activeCategories = filter.getActiveFiltersByType('category');

// Reset filters
afs.filter.resetFilters()

// Add filter groups
afs.filter.addFilterGroup('categories', ['category:tech', 'category:fashion'], 'OR');
afs.filter.addFilterGroup('price', ['price:low', 'price:medium'], 'AND');

// Set how groups combine: AND, OR
afs.filter.setGroupMode('AND'); 

// Remove a group
afs.filter.removeFilterGroup('price');

// Programmatic search
afs.search.search('query');

// Clear search
afs.search.clearSearch();

// Update search configs
afs.search.updateConfig({
    searchKeys: ['title', 'description'],
    minSearchLength: 2,
    highlightMatches: true,
    debounceTime: 300
});

// Basic sort
afs.sort.sort('price', 'asc');

// Multiple criteria sort
afs.sort.sortMultiple([
    { key: 'category', direction: 'asc' },
    { key: 'price', direction: 'desc' }
]);

// Reset sort
afs.sort.reset();

// Custom comparator
afs.sort.sortWithComparator('price', (a, b) => parseFloat(a) - parseFloat(b));
// OR
afs.sort.sortWithOrder('price');

// Goto a specific page
afs.pagination.goToPage(2);

// Change items per page
afs.pagination.setItemsPerPage(15);

// Get pagination info
const info = afs.pagination.getPageInfo();

// Handle state changes
afs.on('urlStateLoaded', (state) => {
    console.log('State loaded:', state);
});

// Manual control
afs.urlManager.updateURL();
afs.urlManager.loadFromURL();
afs.urlManager.clearURL();

// Get specific parameter
const searchQuery = afs.urlManager.getParam('search');

// Presets
afs.filter.savePreset('myFilters');
afs.filter.loadPreset('myFilters');

// Enable Analytics
afs.filter.enableAnalytics((data) => {
  console.log('Filter event:', data);
  // { type: 'filter', filters: [...], visibleItems: 10, timestamp: '...' }
});

// Responsive Options
afs.filter.setResponsiveOptions({
  '768': {
    animationDuration: 200,
    itemsPerPage: 8
  },
  '480': {
    animationDuration: 0,
    itemsPerPage: 4
  }
});

// Set animation options
afs.filter.setAnimationOptions({
  duration: 300,
  type: 'ease-out'
});

// Enable keyboard navigation
afs.filter.enableKeyboardNavigation();

// Shuffle items
afs.filter.shuffle();

8. Event handlers.

Sponsored
afs.filter.on('filter', (data) => {
  console.log('Filter changed:', data);
});

Changelog:

v1.3.3 (04/14/2025)

  • Added a new itemDisplayTypes Map to store the original display types of each item

v1.3.2 (04/05/2025)

  • update

v1.3.1 (04/02/2025)

  • feat: Better search animation filter & pattern

v1.3.0 (03/30/2025)

  • update dependencies
  • fix AFSOptions typo
  • improve logging in AFS class

v1.2.10 (02/24/2024)

  • bugfix

v1.2.8 (11/26/2024)

  • fix: style hover

v1.0.9 (10/27/2024)

  • Add Input range

v1.0.7 (10/26/2024)

  • Refactor code & split as module

The post Filter & Sort DOM Elements with Advanced Filter System appeared first on CSS Script.

rssfeeds-admin

Share
Published by
rssfeeds-admin

Recent Posts

Photos: WE’RE JAMMIN’

Etta Schnackenberg competes during the UMass Ski and Board Club’s WinterFest Rail Jam in Amherst,…

4 seconds ago

Photo: Braving the elements

The post Photo: Braving the elements appeared first on Daily Hampshire Gazette.

12 seconds ago

Peaky Blinders: The Immortal Man Review

Peaky Blinders: The Immortal Man is in select theaters on Friday, March 6, and premieres…

5 minutes ago

‘We Had to Take Nothing Out’ — Extreme Horror Game Hellraiser: Revival Gets Its ESRB Rating

If you’ve seen anything of the upcoming survival horror game Hellraiser: Revival, then you’ll know…

6 minutes ago

AI tools can unmask anonymous accounts

Do you have a Reddit alt, secret X, finsta, or Glassdoor account you trash your…

40 minutes ago

NEP Unveils Modernized EU-03 OB Unit

The post NEP Unveils Modernized EU-03 OB Unit appeared first on TV News Check.

1 hour ago

This website uses cookies.