
Responsive Accordion with JS
Design comparison
Solution retrospective
First time looping through classes using getQuerySelectorAll, its still difficult but i managed to pull it. I like the end result and waiting for feedback.
What challenges did you encounter, and how did you overcome them?removing minus class for buttons of a section when another sections open
Community feedback
- @Grego14Posted about 1 month ago
Hello! Congratulations on completing the challenge. 🎉
I recommend using buttons instead of a
<div>
for the icon elements and clicking on the text next to the icon also expands the accordion, as this would improve the user experience.I see that you're using multiple loops to do things that one would do. You can add an ID to the parent element of all accordions, the accordions-section, then get that element using:
const accordionParent = document.getElementById('accordion-parent-id')
Doing this would no longer require the icons or the text, as you could easily obtain it using the accordionParent variable. And you can use the event delegation technique to improve your code:
accordionParent.addEventListener('click', (event) => { const target = event.target // if the clicked element is not an icon or a accordion text do nothing if(!target.classList.contains('icon') || !target.classList.contains('accordion-header')) return })
To avoid using a loop and removing the minus class from each element, you can simply get the current element that contains the class, remove it, and add it to the currently clicked element:
// inside the accordionParent click event after the **if** // get last open accordion and accordion text const lastOpenAccordion = accordionParent.querySelector('.accordion:has(.minus)') const lastOpenAccordionText = lastOpenAccordion.querySelector('.accordion-content') // get next open accordion and accordion text const clickedAccordion = target.closest('.accordion') const clickedAccordionText = clickedAccordion.querySelector('.accordion-content') lastOpenAccordion.classList.remove('minus') lastOpenAccordionText.classList.remove('open') clickedAccordion.classList.add('minus') clickedAccordionText.classList.add('open') // Handle adding and removing heights ...
The closest method will look up for any first parent element that matches that selector.
When an image is an icon or non-semantic, hide it from screen readers using the aria-hidden attribute with the value true, also remember to add width and height attributes in images to prevent CLS.
<img src="assets/images/icon-star.svg" alt="star SVG" aria-hidden="true" width="40" height="40">
I hope this helps! 😁
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