I have some divs like this:
<div class="item item1" data-tags="sky,sea,roads"></div>
<div class="item item2" data-tags="sea"></div>
<div class="item item3" data-tags="sky,roads"></div>
<div class="item item4" data-tags="roads"></div>
I am trying to make a filter with jQuery so that if I choose "sky", only item1 and item3 will be visible. Here is what I was trying:
$('body').on('click', '.photo-gallery > nav > ul > li > a', function (event) {
var tag = $(this).data('tag');
$('.item').not('.item[data-tags^="'+tag+'"]').fadeOut();
$('.item[data-tags^="'+tag+'"]').fadeIn();
});
This works if the values of data-tags attribute are completely unique as my example above. But I know that it won't work if the tags are something like this:
<div class="item item1" data-tags="skyteck,sea,roads"></div>
<div class="item item2" data-tags="sky,blue sea,loanly roads"></div>
Now if I choose "sky" it will get bot item1 and item2 since they both match "sky".
How can I solve this problem?
I have an idea to solve this, which is selecting all the items and then for each item make comma separated tags as array and then check if my tag is in that object. This will work, but will be somewhat slow. This will be my last option.
$('.item[data-tags*="'+tag+'"]'). Only thing you need to keep in mind that this will treat tag likeskyandblueskyas same.