Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with Accordion and toggling icons

I am trying this for hours, but seems I have somehow a total brain-fart What I want to achieve is making an accordion with toggling icons and sliding up panels. This basically works the minus changes to plus but not when I toggle click the certain header.

$('.accordion-wrapper').on('click', function (e) {
    e.stopPropagation();

    $(this).next('div.accordion-panel').stop(true, false, true).slideToggle();
    // $(this).find('.unalex-plus').toggleClass('glyphicon-plus glyphicon-minus');
    $('div.accordion-panel').not($(this).next('div.accordion-panel')).slideUp();

    if (!$(this).hasClass('active-panel')) {
        $('.accordion-wrapper').find('.unalex-plus').removeClass('glyphicon-minus').addClass('glyphicon-plus');
        $(this).find('.unalex-plus').removeClass('glyphicon-plus').addClass('glyphicon-minus ');
        $(this).addClass("active-panel");
    } else {
        $('this').find('.unalex-plus').removeClass('glyphicon-minus').addClass('glyphicon-plus');
        $('.accordion-wrapper').find('.unalex-plus').removeClass('glyphicon-plus').addClass('glyphicon-plus');
        $(this).removeClass('active-panel');
    }
});

This is my fiddle: https://jsfiddle.net/emd381md/11/

like image 818
Elia Avatar asked Dec 19 '25 06:12

Elia


2 Answers

I've edited your Fiddle.

You shouldn't use addClass and removeClass in that manner. toggleClass is a better (and more readable) solution.

like image 159
Bellu Avatar answered Dec 21 '25 20:12

Bellu


Here is a working demo https://jsfiddle.net/ju9L9rne/13/.

Issues were with the names of classes in the if statement. You were using .unalex-plus which is a class all the accordians have, which is what caused the problems.

So I just changed that class to either .glyphicon-minus or .glyphicon-plus depending on, which was needed.

The changed code:

  if (!$(this).hasClass('active-panel')) {
    $('.accordion-wrapper').find('.glyphicon-minus').removeClass('glyphicon-minus').addClass('glyphicon-plus');
    $(this).find('.glyphicon-plus').removeClass('glyphicon-plus').addClass('glyphicon-minus ');
    $(this).addClass("active-panel");
  } else {
    $('.accordion-wrapper').find('.glyphicon-minus').removeClass('glyphicon-minus').addClass('glyphicon-plus');
    $(this).find('.glyphicon-plus').removeClass('glyphicon-plus').addClass('glyphicon-minus');
    $(this).removeClass('active-panel');
  }
like image 22
Callum Avatar answered Dec 21 '25 19:12

Callum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!