Reputation: 107
I want to create filter buttons for my posts this my html code
<div id='filter'>
<button class='arts'>Arts</button>
<button class='sport'>Sports</button>
<button class='games'>Games</button>
</div>
<div id='posts'>
<div class='post sport'></div>
<div class='post arts'></div>
<div class='post games'></div>
<div class='post games sport'></div>
<div class='post arts'></div>
<div class='post sport'></div>
<div class='post games'></div>
</div>
and i use this jquery code
$("#filter button").each(function() {
$(this).on("click", function(){
var filtertag = $(this).attr('class');
$('.post').hasClass(':not(filtertag)').hide();
});
});
but this not working with me so plz give me the right way to do that
Upvotes: 0
Views: 4318
Reputation: 24638
This should do it; you do not need to use a .each
loop to attach the event listeners to the buttons.
$('.post').hide();//if you want them hidden to start with
$("#filter button").on("click", function(){
var filtertag = $(this).attr('class');
$('.post').hide().filter('.' + filtertag).show();
})
[0].click();//if you want them filtered by first button on load
Upvotes: 0
Reputation: 40038
Try this code. You may need to change the jQuery selectors to work with your live site.
$("button").click(function() {
var show = $(this).attr('class');
$('.post').each(function(){
$(this).show();
var test = $(this).attr('class');
if (test.indexOf(show) < 0) $(this).hide();
});
});
Upvotes: 0