0

I have an interface that can toggle the displaying of help by clicking a caret icon. Previously, I selected and toggled using hard-coded IDs; now, instead, I'm trying to write a generic function to handle everything. Here's an example of my DOM:

<h3 class="box-header">Step 1</h3>
<i class="fa fa-caret-down help-toggle" data-toggle="tooltip" title="Click for help"></i>
<div class="box-body">
    <div class="row">
        <div class="col-md-12">
            <p class="help-text" style="display:none;">This is help for Step 1</p>
        </div>
    </div>
</div>

<h3 class="box-header">Step 2</h3>
<i class="fa fa-caret-down help-toggle" data-toggle="tooltip" title="Click for help"></i>
<div class="box-body">
    <div class="row">
        <div class="col-md-12">
            <p class="help-text" style="display:none;">This is help for Step 2</p>
        </div>
    </div>
</div>

The jQuery function I've written partially works, in that it finds the help-text and toggles its display; however, it is toggling ALL help-texts in unison. I want it to only toggle the closest help-text. Here is the function:

$('.help-toggle').click(function () {
    $(this).toggleClass('fa-caret-up fa-caret-down');
    $(this).closest('.row').find('.help-text').slideToggle("fast");
});

I've done some searching around and found this helpful article but I'm still missing something. Any ideas? Thanks in advance!

Community
  • 1
  • 1
Damon Malkiewicz
  • 393
  • 5
  • 15

2 Answers2

4

Change:

$(this).closest('.row').find('.help-text').slideToggle("fast");

to:

$(this).next('div.box-body').find('.help-text').slideToggle("fast");

.closest() searches up the DOM, and you wanted the node after the help-toggle element.

jsFiddle example

j08691
  • 204,283
  • 31
  • 260
  • 272
0

Try using .first()

$('.help-toggle').click(function () { $(this).toggleClass('fa-caret-up fa-caret-down'); $(this).closest('.row').find('.help-text').first().slideToggle("fast"); });

clovola
  • 378
  • 1
  • 14
  • 2
    `closest()` is not going to work because `.help-toggle` doesn't have an ancestor `.row` – Dave Jun 26 '15 at 20:20
  • 1
    You're right @dave, I read the part of his question that said "it toggles all the help-text" however as-is it toggles nothing, [jsFiddle](https://jsfiddle.net/clovola/f7d73jna/) I am going ot upvote j08691's answer. – clovola Jun 26 '15 at 20:33