There is such an accordion

$( ".category-accordion-head" ).on('click', function(event) { var $otherHeads = $('.category-accordion-head-active').not(this); var $otherContents = $('.category-accordion-content-wrapper').not(this).parent('.category-accordion').find('.category-accordion-content-wrapper'); $(this).toggleClass('category-accordion-head-active'); $otherHeads.removeClass('category-accordion-head-active'); $otherContents.slideUp(); $(this).parent('.category-accordion').find('.category-accordion-content-wrapper').slideToggle(); }); 
 .category-accordion-content-wrapper { display: none; } .category-accordion-head-active { border: solid red 2px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class = "category-accordion"> <h3 class="category-accordion-head">Π—Π°Π³ΠΎΠ»ΠΎΠ²ΠΎΠΊ 1</h3> <div class = "category-accordion-content-wrapper">Π‘ΠΎΠ΄Π΅Ρ€ΠΆΠΈΠΌΠΎΠ΅ 1</div> </div> <div class = "category-accordion"> <h3 class="category-accordion-head">Π—Π°Π³ΠΎΠ»ΠΎΠ²ΠΎΠΊ 2</h3> <div class = "category-accordion-content-wrapper">Π‘ΠΎΠ΄Π΅Ρ€ΠΆΠΈΠΌΠΎΠ΅ 2</div> </div> <div class = "category-accordion"> <h3 class="category-accordion-head">Π—Π°Π³ΠΎΠ»ΠΎΠ²ΠΎΠΊ 3</h3> <div class = "category-accordion-content-wrapper">Π‘ΠΎΠ΄Π΅Ρ€ΠΆΠΈΠΌΠΎΠ΅ 3</div> </div> <div class = "category-accordion"> <h3 class="category-accordion-head">Π—Π°Π³ΠΎΠ»ΠΎΠ²ΠΎΠΊ 4</h3> <div class = "category-accordion-content-wrapper">Π‘ΠΎΠ΄Π΅Ρ€ΠΆΠΈΠΌΠΎΠ΅ 4</div> </div> 

Everything works well until I want to close the active accordion. I do not understand how to do it so that the logic remains as it is now, that is, when clicked, the accordion opens and the title is framed, but the accordion could be closed if desired and the closed accordion would lose the selection frame

    2 answers 2

    You can try this:

     $( ".category-accordion-head" ).on('click', function(event) { var $this = $(this), $parent = $this.closest('.category-accordion'), $otherContents = $parent.find('.category-accordion-content-wrapper'); if( $this.hasClass('category-accordion-head-active') ) { // Ссли Π°ΠΊΡ‚ΠΈΠ²Π½Ρ‹ΠΉ $otherContents.slideUp(function(){ $this.removeClass('category-accordion-head-active'); // это ΠΌΠΎΠΆΠ΅Ρ‚Π΅ вынСсти ΠΈΠ· Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ. Как ΠΏΠΎ ΠΌΠ½Π΅Ρ‚Π°ΠΊ красивСС }); } else { $('.category-accordion').not($parent) .find(".category-accordion-head").removeClass('category-accordion-head-active') .next().slideUp(); $parent .find(".category-accordion-head") .addClass('category-accordion-head-active') .next().slideDown(); } }) 

      You have sty le='display:block' <div class = "category-accordion-content-wrapper"> . You just need to remove it.