0

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

2
  • What's this $('.post-outer') supposed to select? Commented Aug 1, 2014 at 20:45
  • sorry i mean $('.post') Commented Aug 1, 2014 at 20:48

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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();
    });
});

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.