Trying to build a jQuery filter using HTML data attributes

740 views Asked by At

Trying to get and compare the data attribute of the link I click and compare it to anything that it might match in the DOM. 1.) link is clicked (get data-attribute) 2.) take the inner contents of that data-attribute and find anything it might match in the DOM 3.) if there's a match, add class "show" and class "hide" everything else.

I've gotten as far as being able to acquire the contents of the attribute clicked on.

$j(filter_cat_link).click(function(){
    var filter_cat_attr = $j(this).attr("data-category-id");
});

Filter links:

<a data-category-id="breakfast"  href="#">Breakfast</a>    
<a data-tag-id="vegan" href="#">Vegan</a>

Filtered content:

<div data-category-type="breakfast" data-tag-type="vegan" class="recipe col-lg-4 col-md-4 col-sm-4 col-xs-6">    
<div data-category-type="breakfast" data-tag-type="vegan" class="recipe col-lg-4 col-md-4 col-sm-4 col-xs-6">

DOM Objects:

<div data-category-type="4" data-tag-type="1 5 6" class="recipe col-lg-4 col-md-4 col-sm-4 col-xs-6"></div>    
<div data-category-type="5" data-tag-type="1 5" class="recipe col-lg-4 col-md-4 col-sm-4 col-xs-6"></div>

data-category-type= a recipe category such as breakfast(5), dinner(6), etc. data-tag-type= a recipe tag like vegan(1), gluten-free(2), etc.

enter image description here

1

There are 1 answers

3
filur On

Try this:

$j(filter_cat_link).on('click', function(){

    var filter_cat_attr = $(this).data('category-id'),
        $divs = $j('div.recipe'),
        $matches = $divs.filter('[data-category-id="'+ filter_cat_attr + '"]');

    // clear classes
    $divs.removeClass('show hide'); 

    // add show class to matching divs and hide the rest
    $matches.addClass('show');
    $divs.not($matches).addClass('hide');
});

Update:

To search and match elements with multiple values:

var filter_cat_attr = $(this).data('category-id');
    categories = filter_cat_attr & filter_cat_attr.split(' '),
    $divs = $j('div.recipe');

// categories will be an array of categories
// or undefined if no data attribute is present

var $matchies = $divs.filter(function(){
    var $this = $(this), categoryId = $this.data('category-id');
    return ~categories.indexOf(categoryId); // returns true on matching category
});

// do something with $matchies...