I'm working on a CSS Collapsible menu that I created from the tutorial here.
I have a container div that has a button (accordion), that when active, displays content (panel div).
When the button is active, I want to put a border around the container div.
Is there a way I can set .container to active when the child (accordion) is active, so I can target it? Or is there an easier way in CSS?
Any advice anyone has is appreciated. I just can't seem to make it work :(
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}
.container:hover {
border: 1px solid #ededed;
}
.accordion {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
transition: 0.4s;
}
.active,
.accordion:hover {
background-color: #ccc;
}
.panel {
padding: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
}
<div class="container">
<button class="accordion">Button text</button>
<div class="panel">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
</div>
Create a .container.active
class, and toggle it from the JS with this.parentNode.classList.toggle('active');
.
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
this.parentNode.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}
.container:hover {
border: 1px solid #ededed;
}
.container.active {
border: 1px solid black;
}
.accordion {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
transition: 0.4s;
}
.active,
.accordion:hover {
background-color: #ccc;
}
.panel {
padding: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
}
<div class="container">
<button class="accordion">Button text</button>
<div class="panel">
<p>Test 3</p>
</div>
</div>
<div class="container">
<button class="accordion">Button text</button>
<div class="panel">
<p>Test 2</p>
</div>
</div>
<div class="container">
<button class="accordion">Button text</button>
<div class="panel">
<p>Test 3</p>
</div>
</div>