devhustler
devhustler

Reputation: 51

jquery toggle one div when other activated

I really stuck with my code, It's working fine except one thing, I need to close any opened divs, when I click other div to open, here is my code:

function readFaq() {

$('.find-faq-inner h3').prepend('<span id="spanfaq" class="faq-open"></span>');

$('.find-faq-inner h3').each(function () {
    var tis = $(this), state = false;
    var answer = tis.next('div').hide().css('height', 'auto').slideUp();

    tis.click(function () {
        state = !state;
        answer.slideToggle(state);
        tis.toggleClass('active', state);

        if (state == true) {
            tis.find('#spanfaq').removeClass('faq-open');
            tis.find('#spanfaq').addClass('faq-close');
        }
        else {
            tis.find('#spanfaq').removeClass('faq-close');
            tis.find('#spanfaq').addClass('faq-open');
        }

    });
    });
}


<div class="find-faq-inner">
    <div class="text">
    <h3>FAQ1</h3>
    <div>
    text of faq
    </div>
    </div>
</div>

Any ideas would be helpful, Thanks

Upvotes: 2

Views: 307

Answers (1)

Imdad
Imdad

Reputation: 6032

function readFaq() {

$('.find-faq-inner h3').prepend('<span id="spanfaq" class="faq-open"></span>');

$('.find-faq-inner h3').each(function () {
    var tis = $(this), state = false, answer = tis.next('div').hide().css('height', 'auto').slideUp();
    tis.click(function () {
        state = !state;

       $('.find-faq-inner .text div').hide();// This will hide all the divs

        answer.slideToggle(state);
        tis.toggleClass('active', state);

        if (state == true) {
            tis.find('#spanfaq').removeClass('faq-open');
            tis.find('#spanfaq').addClass('faq-close');
        }
        else {
            tis.find('#spanfaq').removeClass('faq-close');
            tis.find('#spanfaq').addClass('faq-open');
        }

    });
    });
}

In the above function I have added $('.find-faq-inner .text div').hide();

This will hide all the divs in the find-faq-inner div, use it accordingly in your code.

To be in more safe you can also use

$('.find-faq-inner .text > div').hide();

It will hide only those divs which are direct child of div of class text

Upvotes: 1

Related Questions