0

I have a (php/html/jquery/css) page where i'm displaying tags at the top (e.g. green, white, fruit, vegetable)

On the page I have divs marked appropriately with classes:

<div class="green fruit">apple</div>
<div class="green vegetable">broccoli</div>

etc.

I'd like to show/hide divs based on which tags have been toggled show/hide.

By default everything is shown. Clicking a tag at the top will toggle the corresponding divs.

The tricky part is to show divs if any of its classes are toggled to 'show' and hide if all of its classes are toggled to hide.

I'm probably making this harder than it needs to be. Thanks for your advice!

2 Answers 2

2

Assuming that you're using buttons to toggle the tags:

<button class="tag" id="toggle-fruit">Fruit</button>
<button class="tag" id="toggle-green">Fruit</button>
<button class="tag" id="toggle-vegetable">Fruit</button>
...

This should work:

var divCollection = $('div'),

    // Gather all tags (store in array):
    tags = $.map(divCollection, function(){
        return this.className.split(' ');  
    }),

    // Object to store enabled tags:
    enabledTags = {};

toggleTags();

$('button.tag').click(function(){

    var tag = this.id.split('-')[1];

    enabledTags[tag] = !enabledTags[tag];

    $(this).toggleClass('toggled'); // Maybe add some CSS?

    toggleTags();

});

function toggleTags() {

    // Hide all divs, then show those that have at least one
    // tag present in the enabledTags object.
    divCollection.hide().filter(function(){

        // Return true if one of classes is found in enabledTags
        return !!$.grep(this.className.split(' '), function(){
            return enabledTags[this];
        }).length;

    }).show();
}

See demo: http://jsbin.com/omota

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

Comments

1

If you first hide, and then show, it should do the trick.

$('#my_divs div').hide();

var tags = ['fruit', 'orange'];
for(var k in tags){
    $('#my_divs div.' + tags[k]).show();
}

1 Comment

A nice, elegant solution. I kicked myself when I saw this. Thanks

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.