Question

So I have a rather basic javascript problem which I have been slamming my head into a wall over for awhile:

<div class='alist'>
   <ul> 
       <li class='group_1'> An Item </li>
       <li class='group_1'> An Item </li>
       <li class='group_2'> An Item </li>
   </ul>
</div>

<div class='alist'>
   <ul> 
       <li class='group_1'> An Item </li>
       <li class='group_1'> An Item </li>
       <li class='group_2'> An Item </li>
   </ul>
</div>


<script>
function toggle_item( num ){
    $$( 'li.group_' + num ).invoke('toggle');
}
</script>

Basically, I need to create a sweeper that sets the div to display:none if all the li are display:none.

I think it would start like:

function sweep(){
    $$('div.alist').each( function( s ) {
      ar = s.down().children
    }); 
} 

Any suggestions for good tutorials would be welcome as well

Was it helpful?

Solution

Something like this might get you started. You'll need to iterate through the children and check if they're visible. If any of them aren't, set a flag and break from the loop. If the flag is false then you don't need to hide the div.

function sweep(){
    $$('div.alist').each( function( s ) {
        var shouldHide = true;
        var children = s.down().childElements();
        children.each(function(li) {
            if(li.visible()) {
                shouldHide = false;
                throw $break;
            }
        });

        if(shouldHide) {
            s.hide();
        }
    }); 
} 

OTHER TIPS

You could use the select() method of Element to find all li descendants. And run a method Array.all for each li and check if all return true. Hide the div if all return true.

function sweep() {
    // check each div
    $$('div.alist').each(function(element) {
        var listItems = element.select('li');
        // are the list items of this div hidden?
        var listItemsHidden = listItems.all(function(item) {
            return item.visible();
        });
        // hide the div too if so
        if(listIemsHidden) {
            element.hide();
        }
    });
}

This code is untested.

This is jQuery solution (Prototype must be something similar):

$('div.alist').css('display', function () {
        return $(this).find('li:visible').length < 1 ? 'none' : '';
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top