Ankita Agrawal
Ankita Agrawal

Reputation: 504

Expand/Collapse not working properly

I want to expand & collapse div. For this I use:-

<ul class="link">
    <li>main link 1<span>[-]</span>
        <ul class="inner_div" style="display:block">
            <li><a>test 1</a></li>
            <li><a>test 2</a></li>
            <li><a>test 3</a></li>
        </ul>
    </li>
</ul>
<ul class="link">
    <li>main link 2<span>[+]</span>
        <ul class="inner_div">
            <li><a>test 1</a></li>
            <li><a>test 2</a></li>
            <li><a>test 3</a></li>
        </ul>
    </li>
</ul>
 <ul class="link">
    <li>main link 3<span>[+]</span>
        <ul class="inner_div">
            <li><a>test 1</a></li>
            <li><a>test 2</a></li>
            <li><a>test 3</a></li>
        </ul>
    </li>
</ul>
 <ul class="link">
    <li>main link 4<span>[+]</span>
        <ul class="inner_div">
            <li><a>test 1</a></li>
            <li><a>test 2</a></li>
            <li><a>test 3</a></li>
        </ul>
    </li>
</ul>

Script is:-

$('.link span').click(function(){
$(".inner_div").hide();
var $ul = $(this).next();
$(this).html( $ul.is(':visible') ? '[+]' : '[&ndash;]');
$ul.slideToggle();

});

Css is:-

.inner_div{ display:none; }
.link span { float: right; cursor: pointer; }

It works but when I click on Expand div again then it should be hide. But It doesn't hide. One more problem is that plus minus sign is not working properly.

Upvotes: 0

Views: 374

Answers (1)

JJJ
JJJ

Reputation: 33163

When you do $(".inner_div").hide() you are hiding the currently open content as well. Later when you say $ul.slideToggle() it will re-open the content (because it's now hidden).

Change it to:

$('.link span').click(function () {
    var $ul = $(this).next();
    $(".inner_div").not( $ul ).hide();
    $( '.link span' ).html( '[+]' );
    if( !$ul.is( ':visible' ) ) {
        $( this ).html( '[&ndash;]');
    }
    $ul.slideToggle();
});

This will also fix the +/- issue.

Demo: http://jsfiddle.net/S7MjY/2/

As a side comment: don't hard-code the initially open menu in the HTML. Instead have all the menu items start out identical and use JavaScript to open the default menu item.

Upvotes: 1

Related Questions