Design comparison
Solution retrospective
A bit of help if possible:
I struggled a bit with the toggle functionality. Toggle by itself works perfect (clicking the same question repeatedly opens/closes it), but in order to have only ONE accordion open at a time, I added a function to remove the previous 'active' classLists from the rest. Doing so, works like intended (only one accordion is open at a time), but it voided the toggle functionality... clicking on the individual question opens it but does not close it if clicked again (only closes if clicking a different question).
I hope this makes sense. If anyone is able to offer insight, I would so appreciate it!
Community feedback
- @DavidMorgadePosted almost 2 years ago
Hello man congrats on finishing the challenge!! great job, the accordition issue is just a bit of logic warm up that will come with time, don't worry much about that.
Here is my approach to solve the problem (for sure there is a better solution, but this should do the trick):
1 - Give each of your faq elements an unique
id
(for example: faq1, faq2, faq3...)2 - Now that we have each faq element with an unique identifier, you can improve your
removeActiveClasses
function so it identifies when the clicked faq is the same that is open:function removeActiveClasses(elementId) { faqs.forEach((faq) => { if (elementId === faq.id) return; faq.classList.remove('active'); }); }
2.1 - The element Id is the id of the faq div that should be pass to the function, then it compares it to the
faq.id
in your foreach loop and if its the same it will instantly return (cutting out the bad behaviour of not letting you close a faq by themself.3 - Last but not least you have to pass the current faq id from your event using some dom traversing or directly getting it from your forEach method:
faqs.forEach((faq) => { faq.addEventListener('click', (e) => { removeActiveClasses(faq.id); faq.classList.toggle('active'); }); });
3.1 - You could also use dom traversing with the
e
Event but this would be overkill since you already have your html faq element from the forEach method, just use faq.id in your eventListener and it should workHope it helps, if you have any questions or need a pull request just ask!
Marked as helpful0@estebanp2022Posted almost 2 years ago@DavidMorgade Thank you David! Your solution was not only able to fix the issue, but your explanation was easy to understand and straight to the point. I'm still learning and often hit a roadblock. I appreciate your help!
0
Please log in to post a comment
Log in with GitHubJoin our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord