简体   繁体   中英

Toggle clickable element style in accordion

This is doing my head in. Sorry if it's a schoolboy error. I have a very straight forward jquery accordion and I can toggle a style on the clickable header for each content by adding a class, but the class does not go when I click to collapse that element itself, only when I expand a sibling. I've popped this on jsfiddle with a simple colour switch.

   $(document).ready(function ($) {
       $('#showHideAccordion').find('h2').click(function () {
           $('.active').removeClass('active');
            //Expand or collapse this panel
           $(this).next().slideToggle('slow');
           $(this).toggleClass('active');
            //Hide the other panels
           $(".podContent").not($(this).next()).slideUp('slow').removeClass('active');
       });
    });

http://jsfiddle.net/wf73o6c6/

When you click the already active item, you remove the active class from it with this line: $('.active').removeClass('active');
then you add it again with this line:
$(this).toggleClass('active');

Making this change to the first line will fix it:
$('.active').not($(this)).removeClass('active');
This way you remove the active class from all the other items, and with the toggleClass line that comes after, you remove the class from the clicked item.

You don't need to remove the class again on your last line, you already took care of that (I see you already used the .not() function here, so your mistake was probably just lack of attention). $(".podContent").not($(this).next()).slideUp('slow');

Also, unrelated, but why $('#showHideAccordion').find('h2') and not just $('#showHideAccordion h2') ?

Here's an updated fiddle: http://jsfiddle.net/wf73o6c6/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM