JoshuaBrand
JoshuaBrand

Reputation: 177

Plus and minus on accordion

Okay so I have a working accordion, which can be seen here

This is my javascript

$(document).ready(function ($) {
    $('#accordion').find('.accordion-toggle').click(function () {

        //Expand
        $(this).next().slideDown('fast');
        $(this).children(".plusminus").text('-');

        //hide other panels
        $(".accordion-content").not($(this).next()).slideUp('fast');

    });
});

obviously in there somewhere I need something along the lines of:

            $(this).next().slideUp('fast');
            $(this).children(".plusminus").text('+');

to make the content boxes close and the - get changed back to a + symbol but I have no idea how I would do this. Any help?

Upvotes: 1

Views: 1010

Answers (1)

Joseph Marikle
Joseph Marikle

Reputation: 78560

There are several ways to do this with selectors, and I'm not entirely sure what is the most efficient, but one method you can do is grab the parent, select its siblings, and find the indicators. Then setting it is easy. Here is this method using your existing code:

demo

$(document).ready(function ($) {
    $('#accordion').find('.accordion-toggle').click(function () {

        //Expand
        $(this).next().slideDown('fast');
        $(this).parent().siblings().find(".plusminus").text('+');
        $(this).children(".plusminus").text('-');

        //hide other panels
        $(".accordion-content").not($(this).next()).slideUp('fast');

    });
});

EDIT:

A much preferred method (in my opinion at least) would be to use a class with a pseudo-element.

demo

$(document).ready(function ($) {
    $('#accordion').find('.accordion-toggle').click(function () {

        //Expand
        $(this).next().slideDown('fast');
        $(this)
          .closest('.accordion-wrap').addClass('active')
          .siblings().removeClass('active');

        //hide other panels
        $(".accordion-content").not($(this).next()).slideUp('fast');

    });
});

then have a class like so

.accordion-wrap .accordion-toggle::after {
    content:'\000a0-';
}
.accordion-wrap.active .accordion-toggle::after {
    content:'\000a0+';
}

Upvotes: 4

Related Questions