Question

I'm struggling with this bit of code, and I'm not sure if it's even possible. I have a list of divs within a single parent element, and I need to collapse and expand certain sets. Here's an example:

<div id="parent">
  <div class="alway_show">ALWAYS SHOW ME</div>
  <div class="collapse_me">COLLAPSIBLE</div>
  <div class="collapse_me">COLLAPSIBLE</div>
  <div class="collapse_me">COLLAPSIBLE</div>
  <div class="alway_show">ALWAYS SHOW ME</div>
  <div class="collapse_me">COLLAPSIBLE</div>
  <div class="collapse_me">COLLAPSIBLE</div>
  <div class="collapse_me">COLLAPSIBLE</div>
</div>

So, in the initial state, .collapse_me will be display:none. There will be a link in always show to expand ONLY the collapsed divs below that particular .always_show div. I know this would be ten million times easier if the collapsible divs were in their own div, but I don't have control over the code. I have to make it work as is using jquery. Possible?

Was it helpful?

Solution

$('div.always_show').nextAll().each(function() {
    if($(this).is('.collapse_me')) {
        $(this).toggle();
    }
    else {
        //this will halt the each "loop", stopping before the next .always_show
        return false; 
    }
});

Of course you should not use my initial selector 'div.always_show', but rather supply it the actual element, which will be the parent of the clicked link. For example:

$('#expand_anchor').parent().parent().nextAll()...

OTHER TIPS

var fncdiv = function(){
    var el = this;
    do{
        el = $(el).next();
        if ($(el).hasClass("collapse_me") )
            $(el).toggle();
        else
            break;

    }while (true) 
};

$('#parent div.alway_show').bind("click", fncdiv);

You shouldn't need to use jQuery. It only requires some clever CSS:

#parent
{
    /* normal parent css here */
}

#parent div
{
  display: block;
}

#parent.collapsed
{
    display: block;
}

#parent.collapsed div
{
  display: none;
}

Selectors are applied in order of specificity. Since '#parent.collapsed div' is more specific than '#parent div', it should override. Now, all you need to do, is set the parent div's class, and you're done. You can use javascript to add/remove the 'collapsed' class to the DIV at runtime to toggle expansion without any additional effort:

// Mootools:
$('parent').addEvent('click', function()
{
  $('parent').toggleClass('collapsed')
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top