Design comparison
Solution retrospective
I'm most proud that I kept my javascript code clean and simple by using a query selector to select the accordion classes, and inside the event listener used a for loop to accomplish the task without much guidance.
What challenges did you encounter, and how did you overcome them?I encountered challenges with planning how to build the accordion with HTML and CSS. There are multiple ways, yet structuring how to use the best structured HTML became the challenge. I eventually used two divs to surround the question text and a hidden box with the description answers.
What specific areas of your project would you like help with?I would like feedback on my approach to the javascript concepts used (for loop) and whether this approach was the best one to accomplish this challenge, and I am open to getting feedback on whether a different javascript concept could be better and why.
Community feedback
- @Grego14Posted 7 months ago
Hello! There is one thing I would change in your JavaScript code to make better use of memory and improve performance: it is the way you add the event listener to each button. Although of course since it is not a project with so many listeners it may not affect performance much.
for (i = 0; i < accordion.length; i++) { accordion[i].addEventListener('click', function () { this.classList.toggle('active') }); }
In this case you are making a loop to iterate through each button and add an eventListener.
I recommend that you use event delegation. Here is a link that explains it: event delegation
Changing your code a little would look like this:
document.addEventListener('click', function(e){ if(e.target.classList.contains('accordion-questions')){ e.target.classList.toggle('active') } })
And here you would be adding only one eventListener to handle the 4 accordions
I hope this helps!
Marked as helpful0
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