Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap Collapsed on load

I use this script

$(function () {
$('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this branch');
$('.tree li.parent_li > span').on('click', function (e) {
    var children = $(this).parent('li.parent_li').find(' > ul > li');
    if (children.is(":visible")) {
        children.hide('fast');
        $(this).attr('title', 'Expand this branch').find(' > i').addClass('icon-plus-sign').removeClass('icon-minus-sign');
    } else {
        children.show('fast');
        $(this).attr('title', 'Collapse this branch').find(' > i').addClass('icon-minus-sign').removeClass('icon-plus-sign');
    }
    e.stopPropagation();
});

http://jsfiddle.net/jhfrench/GpdgF/

for recursive collapsible menu. It works perfectly. But I need the menu collapsed initially that is when the page load and expand only on click.

My JS knowledge is weak. But i tried using toggle(); and hide(); , it results in collapsed and doesnt expand on click

Below is recursive php code

<?php
function listroles($roles)
{
    ?>
    <ul>
    <?php
    foreach($roles as $role)
    {
        ?>
        <li>
            <span><i class="icon-plus "></i> Parent</span> <a href="<?php echo $role['category']->slug; ?>"><?php echo $role['category']->name; ?></a>
            <?php
            if ( ! empty($role['children']))
            {
                listroles($role['children']);
            }
            ?>
        </li>
        <?php
    }
    ?>
    </ul>
    <?php
}

listroles($this->categories_menu);
?> 
like image 343
Shumaise Mohammed Avatar asked Dec 20 '22 20:12

Shumaise Mohammed


1 Answers

You can add a css rule to hide the child li elements at the start

.tree li ul > li {
    display: none;
}

Demo: Fiddle

or hide the child li element on page load

$(function () {
    $('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this branch');

    //hide the child li elements
    $('.tree li ul > li').hide();
    $('.tree li.parent_li > span').on('click', function (e) {
        var children = $(this).parent('li.parent_li').find(' > ul > li');
        if (children.is(":visible")) {
            children.hide('fast');
            $(this).attr('title', 'Expand this branch').find(' > i').addClass('icon-plus-sign').removeClass('icon-minus-sign');
        } else {
            children.show('fast');
            $(this).attr('title', 'Collapse this branch').find(' > i').addClass('icon-minus-sign').removeClass('icon-plus-sign');
        }
        e.stopPropagation();
    });
});

Demo: Fiddle

like image 179
Arun P Johny Avatar answered Jan 02 '23 19:01

Arun P Johny