Issue
I'm trying to toggle the .accordionQuestions div to active once the btn element is clicked:
The hidden .accordionAnswers div is set to display: none on my stylesheet.
Once .accordionQuestions is active, .accordionAnswers is set to display: block.
I've tried looping over the .btn using addEventListener, but no luck so far.
I've tried using parentNode to access .accordionQuestion, and set that to active, but it doesn't seem to work. Any advice is greatly appreciated, thank you for your time!
I'm guessing that the .accordionQuestions.active can't access another div .accordionAnswers, even though it's in the same div. Os there any other way using toggle?
const btns = document.querySelectorAll('.btn')
btns.forEach(btn => {
btn.addEventListener('click', () => {
btn.parentNode.classList.toggle('active')
})
});
.accordionAnswers {
display: none;
}
.accordionQuestions.active .accordionAnswers {
display: block;
}
<div class="accordion">
<div class="accordionQuestions">
<h3>How many team members can I invite?</h3>
<button class="btn"><img src="images/icon-arrow-down.svg"/></button>
</div>
<div class="accordionAnswers">
<p>
You can invite up to 2 additional users on the Free plan. There is no limit on team members for the Premium plan.
</p>
</div>
</div>
<div class="accordion active">
<div class="accordionQuestions">
<h3>What is the maximum file upload size?</h3>
<button class="btn"><img src="images/icon-arrow-down.svg" /></button>
</div>
<div class="accordionAnswers">
<p>
No more than 2GB. All files in your account must fit your allotted storage space.
</p>
</div>
</div>
Solution
The issue is because .accordionAnswers is not a child of .accordionQuestions, they're siblings. You need to use the + operator in your CSS selector:
.accordionQuestions.active + .accordionAnswers {
display: block;
}
Here's a full working example:
const btns = document.querySelectorAll('.btn')
btns.forEach(btn => {
btn.addEventListener('click', () => {
btn.parentNode.classList.toggle('active')
})
});
.accordionAnswers {
display: none;
}
.accordionQuestions.active + .accordionAnswers {
display: block;
}
<div class="accordion">
<div class="accordionQuestions">
<h3>How many team members can I invite?</h3>
<button class="btn"><img src="images/icon-arrow-down.svg"/></button>
</div>
<div class="accordionAnswers">
<p>
You can invite up to 2 additional users on the Free plan. There is no limit on team members for the Premium plan.
</p>
</div>
</div>
<div class="accordion active">
<div class="accordionQuestions">
<h3>What is the maximum file upload size?</h3>
<button class="btn"><img src="images/icon-arrow-down.svg" /></button>
</div>
<div class="accordionAnswers">
<p>
No more than 2GB. All files in your account must fit your allotted storage space.
</p>
</div>
</div>
Answered By - Rory McCrossan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.