Mohamed Abo ElGhranek
Mohamed Abo ElGhranek

Reputation: 107

Create filter buttons using jQuery

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

Answers (3)

PeterKA
PeterKA

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

DEMO

Upvotes: 0

cssyphus
cssyphus

Reputation: 40038

Try this code. You may need to change the jQuery selectors to work with your live site.

jsFiddle Demo

$("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

putvande
putvande

Reputation: 15213

You are passing in the literal string "filtertag", not the variable, so you need to do the following:

$('.post').show(); // Show all posts
$('.post:not(.' + filtertag + ')').hide(); // Hide the ones you don't want

Fiddle

Upvotes: 3

Related Questions