MDez
MDez

Reputation: 681

Jquery Toggle Loop

I'm using this particular script for specific expand/collapse items and have decided i'd like to be able to toggle multiple objects on the same page but im not sure exactly how do make that happen. Can anybody provide any insight?

$('#faq_info_header').click(function() {
    $('#faq_info_exp').toggle();
    var arrow = $('#faq_info_header').find('.fa');
    if (arrow.hasClass('fa-arrow-right')) {
        arrow.removeClass('fa-arrow-right');
        arrow.addClass('fa-arrow-down');
    } else if (arrow.hasClass('fa-arrow-down')) {
        arrow.removeClass('fa-arrow-down');
        arrow.addClass('fa-arrow-right');
    }
    return false;
});

HTML as requested:

<a id="faq_info_header">This is the question? <i class="fa fa-arrow-right"></i></a>

<div id="faq_info_exp" style="display:none;">This is the hidden content</div>

Upvotes: 1

Views: 2227

Answers (1)

jme11
jme11

Reputation: 17407

You can use toggleClass (more here http://api.jquery.com/toggleClass/) by replacing your entire if statement with:

arrow.toggleClass('fa-arrow-right fa-arrow-down');

Okay, now I think I understand the question. Here is a fiddle

HTML:

<div class="faqs">
    <div class="faq_item">
        <p>This is the question 1? <i class="fa fa-arrow-right"></i>
        </p>
        <div class="faq_info_exp">This is the hidden content 1</div>
    </div>
    <div class="faq_item">
        <p>This is the question 2? <i class="fa fa-arrow-right"></i>
        </p>
        <div class="faq_info_exp">This is the hidden content 2</div>
    </div>
    <div class="faq_item">
        <p>This is the question 3? <i class="fa fa-arrow-right"></i>
        </p>
        <div class="faq_info_exp">This is the hidden content 3</div>
    </div>
</div>

JS:

$('.faqs').on('click', '.faq_item', function () {
    $(this).children('.faq_info_exp').toggle();
    $(this).find('i').toggleClass('fa-arrow-right fa-arrow-down');
});

CSS:

.faq_info_exp {
    display: none;
}

Basically what I did was:

  1. I created a couple of more question & answer pairs for demonstration.
  2. I surrounded all of them with a div and added a class to it called "faqs". This way we can use event delegation and have only one event handler being created versus lots of them.
  3. I wrapped each of the questions and corresponding answer in a div and gave it a class of "faq-item". Now we can use that in our handler and determine which div dispatched the event and use $(this) to refer to it easily.
  4. Then $(this).children('.faq_info_exp').toggle(); finds the direct child element with the class faq_info_exp and toggles it.
  5. Finally, $(this).find('i').toggleClass('fa-arrow-right fa-arrow-down'); finds the descendant element <i> and toggles the class.

Upvotes: 2

Related Questions