Design comparison
Solution retrospective
The logic of this challenge was complicated for me. I couldn't make it so that only one of the questions could be open at a time without getting errors. In the end I decided to leave it like that.
Community feedback
- @JimTK16Posted 11 months ago
Hi Yarcefm, I have just finished this challenge. My solution for keeping only one question open is as below:
- Creat an array of question.
- Loop through the array and select the questions that aren't active with the filter() method. Then remove the active class from all of them.
- Finally, we can toggle the active class of the question that the user clicked. Link to my github solution: https://github.com/JimTK16/faq-accordion. Hope it helps
Jim
1 - @YarceFMPosted 11 months ago
Thank you very much, your request helped me a lot. What I was trying to do was that when I clicked on any of the questions it would give a display = none to all the answers and then give the display = block to the answer I was clicking on but it gave an error and I couldn't solve it. Thank you very much for the help.
0@JimTK16Posted 11 months agoHi @YarceFM, below is how I implement the solution based on your code:
const questions = document.querySelectorAll(".question"); //create an array of questions const questionsArray = Array.from(questions); const clickHandler = (question) => { // loop through the questionsArray to close all OTHER questions questionsArray .filter((item) => item !== question) .map((item) => { const answer = document.querySelector(item.dataset.target); answer.style.height = null; }); // Seleccionar la respuesta correspondiente console.log(question); const answer = document.querySelector(question.dataset.target); // Cambiar la altura de la respuesta if (answer.style.height) { answer.style.height = null; } else { answer.style.height = answer.scrollHeight + "px"; answer.style.marginTop = "24px "; } // Cambiar el estilo de fondo del icono const icon = question.querySelector(".slice-icon"); if (answer.style.height) { icon.style.backgroundImage = "url(/FAQ-accordion/assets/images/icon-minus.svg)"; } else { icon.style.backgroundImage = "url(/FAQ-accordion/assets/images/icon-plus.svg)"; } }; questionsArray.forEach((question) => { question.addEventListener("click", () => { clickHandler(question); }); });
1
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