Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jQuery: How do I make an already open accordion slide collapse when I click on a different slide?

Working codepen link: https://codepen.io/boingloings33/pen/PoXpLWR

I have a mostly functioning accordion that I’m struggling to make auto-collapse an open slide when I click the next one. Any help would be greatly appreciated, thank you.

HTML:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<body>
    <div class="container">
      <div class="accordion" id="accordion-1">
        <div class="head">
          <h2>Title 1</h2>
        </div>
        <div class="content">
          <p> lorem ipsum </p>
        </div>
      </div>

      <br />

      <div class="accordion" id="accordion-2">
        <div class="head">
          <h2>Title 2</h2>
          <i class="fas fa-angle-down arrow"></i>
        </div>
        <div class="content">
         <p> lorem ipsums </p>
        </div>
      </div>
</body>

JS:

jQuery(function () {
  $(".head").on("click", function () {
    $(this).toggleClass("active");
    $(this).parent().find(".arrow").toggleClass("arrow-animate");
    $(this).parent().find(".content").slideToggle(280);
  });
});

CSS:

.accordion {
  box-shadow: 0px 1px 7px #dbdbdb;
}

.accordion .head {
  background-color: #ffffff;
  color: #563e6e;
  padding: 20px 30px;
  cursor: pointer;
  transition: 0.2s ease;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.accordion .head:hover,
.accordion .active {
  background-color: #ffe77aff;
}
.accordion .content {
  background-color: #ffffff;
  display: none;
  padding: 20px 30px;
  color: #333333;
}

>Solution :

Replace the js code with the below code

jQuery(function () {
            $(".head").on("click", function () {              
                let isActive = $(this).hasClass('active');
                $(".head").removeClass('active');
                $(".head").parent().find(".content").slideUp(280);
                $(".head").parent().find(".arrow").removeClass("arrow-animate");
                if (isActive == false) {
                    $(this).addClass('active')
                    $(this).parent().find(".arrow").addClass("arrow-animate");
                    $(this).parent().find(".content").slideDown(280);
                }
            });
        });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading