Coder Wrap provides free to use snippets Coder Wrap provides free to use snippets

Back to Accordions
Preview Source Code
Download
HTML
CSS
/*Typeo CSS Start*/
 @import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,400;0,500;0,600;0,700;1,400&display=swap');
*{ box-sizing: border-box;}
body {
  font-family: 'Poppins', sans-serif;
  color: #222;
  margin: 0;
  font-weight: 300;
}

/*Typeo CSS End*/
.content {
  max-width: 1000px;
  width: 100%;
  display: flex;
  margin: auto;
  flex-flow: row wrap;
  align-items: center;
  justify-content: center;
}
.content>div {
  width: 50%;
}
.accordion .title {
  border: 1px solid #ddd;
  padding: 8px 15px;
  border-radius: 3px;
  cursor: pointer;
  transition: 0.3s;
  margin-bottom: 10px;
  position: relative;
}
.accordion .title.active {
    background-color: #203049;
    color: #fff;
}
.accordion .title:after {
  content: '';
  width: 10px;
  height: 10px;
  border-left: #000 2px solid;
  border-bottom: #000 2px solid;
  position: absolute;
  right: 14px;
  top: 50%;
  margin-top: -10px;
  transform: rotate(-45deg);
}
.accordion .title.active:after {
  border-color: #fff;
  transform: rotate(-134deg);
  margin-top: -6px;
}
.desc {
  padding: 15px;
  display: none;
}
.desc.active {
  display: block;
}
.image {
  text-align: right
}
.image img {
  height: 370px;
}
@media(max-width:992px) {
.content>div {
    width: 100%;
}
}
JS
// Set first title and description to active
document.querySelector('.accordion .title:first-child').classList.add('active');
document.querySelector('.accordion .desc:nth-child(2)').style.display = 'block';

// Add event listeners to titles
const titles = document.querySelectorAll('.accordion .title');
titles.forEach(function (title) {
  title.addEventListener('click', function () {
    // Add active class to clicked title
    title.classList.add('active');

    // Remove active class from all other titles
    titles.forEach(function (otherTitle) {
      if (otherTitle !== title) {
        otherTitle.classList.remove('active');
      }
    });

    // Slide up all other descriptions
    const descriptions = document.querySelectorAll('.accordion .desc');
    descriptions.forEach(function (desc) {
      if (!desc.classList.contains('active')) {
        desc.style.display = 'none';
      }
    });

    // Slide down the clicked description
    const clickedDesc = title.nextElementSibling;
    clickedDesc.style.display = 'block';

    // Change image source
    const dataImage = title.getAttribute('data-image');
    const image = document.querySelector('.image img');
    image.setAttribute('src', dataImage);
  });
});

Related Snippets

Leave a comment

Your email address will not be published. Required fields are marked *