2
\$\begingroup\$

I have the following code to open and close some popup divs. I'd like to know whether there is a shorter solution to close the currently opened divs, as soon as another div is opened, so that there is only one open div.

The current solution works as you can see in this jsFiddle, but I guess it is a bit inconvenient.

jQuery:

$('.details').hide();
$('#item-a').click(function () {
$('#detail-1').fadeToggle(600);
 $('#detail-2,#detail-3').fadeOut("slow");
});

$('#item-b').click(function () {
$('#detail-2').fadeToggle(600);
 $('#detail-1,#detail-3').fadeOut("slow");
});

$('#item-c').click(function () {
$('#detail-3').fadeToggle(600);
 $('#detail-1,#detail-2').fadeOut("slow");
});

$('.btn-close').click(function () {
 $(this).parent().parent().fadeOut("slow");
});

HTML:

<div id="content">
<ul class="list-1">
    <li class="topic-a" id="item-a">
        <p class="shortinfo"> item a </p>
    </li>
    <li class="topic-b" id="item-b">
        <p class="shortinfo"> item b </p>
    </li>
    <li class="topic-b" id="item-c">
        <p class="shortinfo"> item c </p>
    </li>
 </ul>
</div>
<div class="block">
  <div class="details" id="detail-1">
    <p><a class="btn-close">close</a>
    </p>
    <p> Some detailed text 1.. </p>
  </div>
  <div class="details" id="detail-2">
    <p><a class="btn-close">close</a>
    </p>
    <p> Some detailed text 2.. </p>
  </div>
  <div class="details" id="detail-3">
    <p><a class="btn-close">close</a>
    </p>
    <p> Some detailed text 3.. </p>
  </div>
 </div>
\$\endgroup\$
2
\$\begingroup\$

You can use the not function to get all the details elements except one:

function show(sel) {
  var el = $(sel);
  el.fadeToggle(600);
  $('.details').not(el).fadeOut("slow");
}

$('.details').hide();

$('#item-a').click(function () {
  show('#detail-1');
});

$('#item-b').click(function () {
  show('#detail-2');
});

$('#item-c').click(function () {
  show('#detail-3');
});

$('.btn-close').click(function () {
  $(this).parent().parent().fadeOut("slow");
});
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.