Search code examples
jquerytoggleeachclosestsiblings

jQuery toggle opacity with same class


I have 3 divs all with the same class. Within each div is a h3 and a hidden div with a class of 'content'.

If the h3 is clicked in any of these divs then the corresponding 'content' div is shown.

If any h3 is clicked and the 'content' div expands then the sibling 'example' divs should fade out to opacity 0.5

When all 'content' divs are closed then the 'example' divs should not be faded out.

I currently can't get the 'example' divs to not be faded when all the 'content' divs are closed.

CSS

.fade {opacity:0.5;}
.content {display:none;}

JS

$(function () {
    $(".example .titlename").click(function () {
    $(this).closest('.example').find('.content').slideToggle(500);
    $(this).closest('.example').toggleClass('active').siblings().not('.active').css({ opacity: 0.5 });
    $(this).closest('.example').not('.active').css({ opacity: 0.5 });
    $(this).closest('.example.active').css({ opacity: 1.0 });
    });

});

HTML

<div class="example">
    <h3 class="titlename">Test titles 1</h3>
    <div class="content">content1</div>
</div>

<div class="example">
    <h3 class="titlename">Test titles 2</h3>
    <div class="content">content2</div>
</div>

<div class="example">
    <h3 class="titlename">Test titles 3</h3>
    <div class="content">content3</div>    
</div>

JSFiddle is here with example code: http://jsfiddle.net/Lgf4s/

Any help gratefully accepted!


Solution

  • You need to check if all examples are closed in the complete function of the slideToggle

    http://jsfiddle.net/Lgf4s/2/

    $(this).closest('.example').find('.content').slideToggle(500, function() {
        // check if any example is active
        if(!$('.example').hasClass('active')) {
            $('.example').css('opacity', '1');
        }
    });
    

    I also cleaned it up a bit caching some jquery elements