Design comparison
Solution retrospective
need feedback so i ca n improve my code
Community feedback
- @TsiolisPosted about 3 years ago
Hi Shahzaib
Good job on completing the challenge!
One way to improve your code would be to give each accordion question a class name and add an event listener to show the answer, ill paste a code example to this below.
HTML
<button class="accordion">Section 1</button> <div class="panel"> <p>Lorem ipsum...</p> </div> <button class="accordion">Section 2</button> <div class="panel"> <p>Lorem ipsum...</p> </div> <button class="accordion">Section 3</button> <div class="panel"> <p>Lorem ipsum...</p> </div>
CSS
.accordion { background-color: cadetblue; color: black; font-weight: bold; cursor: pointer; padding: 18px; width: 100%; text-align: left; border: none; outline: none; transition: 0.4s; }
.panel { padding: 0 18px; background-color: white; display: none; overflow: hidden; }
JS
const acc = document.getElementsByClassName("accordion"); let i;
for (i = 0; i < acc.length; i++) { acc[i].addEventListener("click", function() { /* Toggle between adding and removing the "active" class, to highlight the button that controls the panel */ this.classList.toggle("active");
/* Toggle between hiding and showing the active panel */ const panel = this.nextElementSibling; if (panel.style.display === "block") { panel.style.display = "none"; } else { panel.style.display = "block"; }
}); }
I learned how to do this by reading the tutorial at https://www.w3schools.com/howto/howto_js_accordion.asp (I have updated some of the syntax to ES6).
I would also recommend reading about the HMTL <detail> element, which provides an accordion-type feature without having to use any Javascript.
If you have any questions about this I will do my best to answer.
Happy coding!
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