user1621945
user1621945

Reputation: 35

Get all divs by data attribute until

Creating a dynamic, multi-level jquery accordion menu of sorts, however using divs instead of the usual li tags.

Each div has a data attribute (data-level), and values are 1, 2, 3, 4, etc...

My "toggle" function needs to show/hide each div that has a greater data-level than it's own, until it reaches a div with a data-level that matches it's own...

so if I have:

<div data-level="1">Sample Title</div>
    <div data-level="2">Sample Subtitle</div>
        <div data-level="3">Sample Subsubtitle</div>
    <div data-level="2">Sample Subtitle</div>

<div data-level="1">Sample Title</div>
    <div data-level="2">Sample Subtitle</div>
        <div data-level="3">Sample Subsubtitle</div>

Then clicking on the first "Sample Title" would toggle both "Sample Subtitle" and the "Subsubtitle", but not touch the second "Sample Title" or its children... And of course, clicking on a "Subtitle" would toggle it's "Subsubtitle", but not affect any other elements.

Any advice?

Upvotes: 0

Views: 758

Answers (1)

musicnothing
musicnothing

Reputation: 3985

Check out this Fiddle: http://jsfiddle.net/p4gps/1/

The key is in this code:

$('div').click(function() {
    var level = parseInt($(this).data('level'));
    if ($(this).hasClass('show')) {
        $(this).removeClass('show');
        $(this).nextAll('div').each(function() {
            if (parseInt($(this).data('level')) > level) $(this).hide().removeClass('show');
            else return false;
        });
    } else {
        $(this).addClass('show');
        $(this).nextAll('div').each(function() {
            if (parseInt($(this).data('level')) > level) $(this).show().addClass('show');
            else return false;
        });
    }
});

It does a $.each on all the div elements that come after the one you clicked on. Once it reaches a div that is at the same level or lower, it breaks out of the loop.

Upvotes: 1

Related Questions