javascriptjqueryfiltermixitup

Show count of filtered Items on initial page load Mixitup


I'm using MixItUp 3 to sort and filter items and want to display the count of items within each filter category on initial page load. I've already tried the example from SO (mixitup counting visible items on initial start after page loading) but its MixItUp 2 and didn't work in my case.

I want to show the filtered items count within each control filter as such:

    <div class="controls btn-toolbar d-flex justify-content-between mb-2" role="toolbar" aria-label="Toolbar with button groups">
        <div class="btn-group" role="group" aria-label="First group">
            <button type="button" data-mixitup-control class="control btn btn-secondary badge-pill" data-filter=".filter-1">Filter 1
                <span class="badge badge-light ml-1" id="count1">{Show Items Count}</span>
            </button>
            <button type="button" data-mixitup-control class="control btn btn-secondary badge-pill" data-filter=".filter-2">Filter 2
                <span class="badge badge-light ml-1" id="count2">{Show Items Count}</span>
            </button>
        </div>
    </div>

It is supposed to be displayed inside this span (from above example):

<span class="badge badge-light ml-1">{Show Items Count}</span>

So far my MixItUp mixer looks like this:

    var mixer = mixitup(containerEl, {
        animation: {
            effects: 'fade translateZ(-100px) stagger(100ms)',
            easing: 'cubic-bezier(0.645, 0.045, 0.355, 1)',
            staggerSequence: function(i) {
                return i % 3;
            },
            duration: 300,
            applyPerspective: false
        },
        selectors: {
            control: '[data-mixitup-control]'
        }
    });

From the other Examples i've learned that I need to use the state.totalShow and from the MixItUp Documentation i've seen that there is the load functionality but I didn't find a solution for my needs.


Solution

  • I Have found a solution which is probably not written in the most performant and best practise way but it works for me.

    First, I am getting the mixer state via

    var state = mixer.getState();
    

    And then I am iterating through the state.targets object and searching for matching selectors within the ClassList.value and adding them together. Then the added up value is parsed to the span element, which looks like this:

    var count1 = 0;
    var count2 = 0;
    
    $.each( state.targets, function( index, value ) {
        if (this.classList.value.match('filter-1')) {
            count1 += this.classList.value.match('filter-1').length;
            $('#count1').html(count1);
        }
    });
    
    $.each( state.targets, function( index, value ) {
        if (this.classList.value.match('filter-2')) {
            count2 += this.classList.value.match('filter-2').length;
            $('#count2').html(count2);
        }
    });