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>
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jul 7, 2013 at 20:17
\$\endgroup\$

1 Answer 1

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");
});
answered Jul 7, 2013 at 21:30
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.