Search code examples
javascriptjquerytogglefade

Using fadeToggle + fade all other when having set of divs


I have set of divs inside one container div called: "people".
each div is called "people-box"
inside each "people-box" I have a div called: "people-description"

So this will describe my hierarchy:

<div class="people">

  <div class="people-box">
    <div class="people-description"></div>
  </div>

  <div class="people-box">
    <div class="people-description"></div>
  </div>

  <div class="people-box">
    <div class="people-description"></div>
  </div>

</div> 

I would like to trigger to actions here:
when someone is clicking on "people-box" div I want to fade toggle the description, simply show and hide

it is working using this method:

$('.people-box').click(function(){
        $(this).find('.people-description').fadeToggle(500);

});

however, this is working only when I am on the same div clicking to show the description and clicking again to hide it. if the description is shown and I am clicking on another "people-box" it is not fading the one that is shown..
I would like that too work (toggling the description clicking the same div) but also when moving to another "people-box" I would like to fade out all others that left open

Will appreciate any solution
Thanks


Solution

  • Fade out all description by doing

    $('.people-description').fadeOut(500);
    

    all together

    $('.people-box').click(function(){
        var $el = $(this).find('.people-description');
        $('.people-description').not($el).fadeOut()
        $el.fadeToggle(500);
    });
    

    The 500 milliseconds is optional, change it if you need to

    http://jsfiddle.net/65w90pqj/1/

    Update:

    $('.people-box').click(function (e) {
        if (!$(e.target).hasClass('people-description')) {
            var $el = $(this).find('.people-description');
            $('.people-description').not($el).fadeOut()
            $el.fadeToggle(500);
        }
    });
    

    http://jsfiddle.net/65w90pqj/2/