1

See my current code here: http://jsfiddle.net/swQLg/3/

I have some div's like

<div class="qtn">question1</div>
<div class="ans">answer1</div>
<div class="qtn">question2</div>
<div class="ans">answer2</div>
<div class="qtn">question3</div>
<div class="ans">answer3</div>
<div class="qtn">question4</div>
<div class="ans">answer4</div>

my jquery function is

$(document).ready(function () {
    $(".qtn").on('click', function () {
        $(this).next(".ans").slideToggle();
    });
});

When I show one answer, I would like it to hide the other answers if they are showing.

3
  • Did you mean that you wanted to hide all div's on click, apart from the one you're opening? Sep 17, 2013 at 18:11
  • you want to have only one answer div opened at a time.right?
    – Raghu
    Sep 17, 2013 at 18:12
  • Nevermind, two spot-on answers have already done it :) Sep 17, 2013 at 18:12

2 Answers 2

4

Try this:

$(document).ready(function () {
    $(".qtn").on('click', function () {
        var $ans = $(this).next(".ans");
        $ans.slideToggle(); //toggle the current one
        $(".ans").not($ans).slideUp(); //hide the others
    });
});

Fiddle

The reason I save $(this).next(".ans"); to a variable is for performance. If I didn't do this, every time that you call $(this).next(".ans");, jQuery would have to wrap this into a jquery object and then perform the next() function on that jquery object. In this case that would only be 1 extra time, but that still means 2 unnecessary operations.

Here is a jsperf test demonstrating the difference.

2

Put slideUp() in your click event to slide everything up. This will take care of closing/hiding already open divs and then put your code.

Demo

$(document).ready(function () {
    $(".qtn").on('click', function () {
        $(".ans").not($(this).next(".ans")).slideUp(); // slide the rest up
        $(this).next(".ans").slideToggle();
    });
});

Edited to fix what @smerny pointed out.

1
  • 1
    This will hide, and then show the current element when the user tries to hide it.
    – Smern
    Sep 17, 2013 at 18:12

Your Answer

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

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