I have a collapsible component made with javascript. I want it to work so that when you click the icon the menu drops down/collapses. The way that it is currently working is that if you click anywhere on the entire line this rule applies.
const collapsibles = document.querySelectorAll(".collapsible");
collapsibles.forEach((item) =>
item.addEventListener("click", function() {
this.classList.toggle("collapsible--expanded");
})
);
.collapsible__header {
display: flex;
justify-content: space-between;
}
.collapsible__heading {
margin-top: 0;
}
.collapsible__chevron {
transform: rotate(-90deg);
transition: transform 0.3s;
}
.collapsible__content {
max-height: 0;
overflow: hidden;
opacity: 0;
transition: all 0.5s;
}
.collapsible--expanded .collapsible__chevron {
transform: rotate(0);
}
.collapsible--expanded .collapsible__content {
max-height: 100vh;
opacity: 1;
}
.collapsible .icon {
height: 50px;
width: 50px;
}
<div class="collapsible">
<header class="collapsible__header">
<h2 class="collapsible__heading">Item 1</h2>
<svg class="icon icon--white collapsible__chevron">
<use xlink:href="images/integratesprite.svg#chevron"></use>
</svg>
</header>
<div class="collapsible__content">
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Corrupti, adipisci.
</div>
</div>
I had to add a span with the class of the SVG since the SVG is invisible.
The code should work on the svg if you remove the span
document.querySelector(".collapsible__chevron").addEventListener("click", function(e) {
this.closest(".collapsible").classList.toggle("collapsible--expanded");
})
.collapsible__header {
display: flex;
justify-content: space-between;
}
.collapsible__heading {
margin-top: 0;
}
.collapsible__chevron {
transform: rotate(-90deg);
transition: transform 0.3s;
}
.collapsible__content {
max-height: 0;
overflow: hidden;
opacity: 0;
transition: all 0.5s;
}
.collapsible--expanded .collapsible__chevron {
transform: rotate(0);
}
.collapsible--expanded .collapsible__content {
max-height: 100vh;
opacity: 1;
}
.collapsible .icon {
height: 50px;
width: 50px;
}
<div class="collapsible">
<header class="collapsible__header">
<h2 class="collapsible__heading">Item 1</h2><span class="icon icon--white collapsible__chevron">▼</span>
</header>
<div class="collapsible__content">
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Corrupti, adipisci.
</div>
</div>