JV10
JV10

Reputation: 891

Toggle closest div hide other open divs

The following code allows me to toggle a div inside an LI, how can I adjust it so that when one div is open all other divs inside sibling LI's are closed?

$(document).ready(function () {  
$('.grey_button a').toggle(function() {
    $(this).closest('li').find('.job_description').fadeIn(0);
    $(this).toggleClass('open');
    //$(this).text($(this).text() == 'More Information' ? 'Hide Information' : 'More Information');
    return false;
},
    function() {
      $(this).closest('li').find('.job_description').fadeOut(0);
      $(this).toggleClass('open');
      //$(this).text($(this).text() == 'Hide Information' ? 'More Information' : 'Hide Information');
    return false;
  });
});

Example of HTML

<ul>
  <li>
    <div class="grey_button"><a href="" class="arrow">More information</a></div>
    <div class="job_description" style="display: none; ">
      Lorem ipsum
    </div>
  </li>
  <li>
    <div class="grey_button"><a href="" class="arrow">More information</a></div>
    <div class="job_description" style="display: none; ">
      Lorem ipsum
    </div>
  </li>
  <li>
    <div class="grey_button"><a href="" class="arrow">More information</a></div>
    <div class="job_description" style="display: none; ">
      Lorem ipsum
    </div>
  </li>
</ul>

Upvotes: 0

Views: 1887

Answers (3)

adeneo
adeneo

Reputation: 318202

I'd do:

$(document).ready(function () {  
    $('.grey_button a').on('click', function(e) {
        e.preventDefault();
        $('.job_description').not($(this).closest('li').find('.job_description')).hide();
        $(this).toggleClass('open').parent('div').next('.job_description').toggle();
    });
});​

FIDDLE

Upvotes: 0

charlietfl
charlietfl

Reputation: 171669

You could just add one lookup for all $('.job_description').hide().

If this would impact other sections of page with same class:

$('.grey_button a').toggle(function() { /* cache parent el */
    var $parent = $(this).closest('li'),
        $list = $parent.parent();
    $list.find('.job_description').hide();
    $list.find('.open').removeClass('open')

    $parent.find('.job_description').fadeIn(0);

    $(this).toggleClass('open');
    //$(this).text($(this).text() == 'More Information' ? 'Hide Information' : 'More Information');
    return false;
}, function() {
    $(this).closest('li').find('.job_description').fadeOut(0);
    $(this).toggleClass('open');
    //$(this).text($(this).text() == 'Hide Information' ? 'More Information' : 'Hide Information');
    return false;
});
});

Upvotes: 1

elclanrs
elclanrs

Reputation: 94101

In this situation I think you might be able to reduce your code quite a bit:

$('.grey_button a').click(function(e) {
    e.preventDefault();
    $('.job_description').hide(); // Reset
    $(this).closest('.job_description').fadeToggle();
    $(this).toggleClass('open');
});

Upvotes: 0

Related Questions