DEV Community

ktr92
ktr92

Posted on

[jquery] The most simple universal accordion

DEMO - https://codepen.io/ktr92/pen/zYyoYeW

HTML

<div class='accordion_title' data-accordiontitle='accordion1'>
  Title 1
</div>
<div class='accordion_content' data-accordioncontent='accordion1'>
  Content 1
</div>

<div class='accordion_title' data-accordiontitle='accordion2'>
  Title 2
</div>
<div class='accordion_content' data-accordioncontent='accordion2'>
  Content 2
</div>
Enter fullscreen mode Exit fullscreen mode

CSS

[data-accordioncontent] {
  display: none;
}

[data-accordiontitle] {
  position: relative;
  display: block; 
  cursor: pointer;
}
[data-accordiontitle]:after {
  content: "+";
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  right: 10px;
  display: inline-block;
  vertical-align: middle;
  width: 30px;
  height: 30px;
  text-align: center;
  color: #fff;
  line-height: 30px;
  font-size: 20px;
  font-weight: 700;
  margin-right: 5px;
  background-color: #c9c9c9;
  border-radius: 50%;
  -webkit-transition: all 0.2s ease-out;
  transition: all 0.2s ease-out;
}
[data-accordiontitle].active:after {
  content: "-";
}

[data-accordioncontent] {
  padding: 20px;
}
Enter fullscreen mode Exit fullscreen mode

JS

$("[data-accordiontitle]").on("click", function () {
  let accordion = $(this).data("accordiontitle");
  $(`[data-accordioncontent="${accordion}"`).slideToggle();
  $(this).toggleClass("active");
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)