Design comparison
SolutionDesign
Solution retrospective
Feel free to comment! Every tip is a step further for me :)
Community feedback
- @aykinsancakliPosted 10 months ago
Feedback on FAQ Accordion JavaScript Implementation
Hello,
I've carefully examined your JavaScript code for the FAQ accordion, and I believe there's an opportunity to enhance it for better efficiency and readability. Below is an improved version:
Improved Accordion Functionality
// Select all elements with the class 'question-box' const questionBoxes = document.querySelectorAll('.question-box'); // Function to toggle the answer box and update the SVG icon function toggleAnswer(box) { // Toggle the 'open' class to show/hide the answer box box.classList.toggle('open'); // Select the SVG element within the clicked question box const svgEl = box.querySelector('svg'); // Update the SVG path based on whether the box is open or not if (box.classList.contains('open')) { svgEl.innerHTML = '<path fill="#301534" d="M15 3.313A12.187 12.187 0 1 0 27.188 15.5 12.2 12.2 0 0 0 15 3.312Zm4.688 13.124h-9.375a.938.938 0 0 1 0-1.875h9.374a.938.938 0 0 1 0 1.876Z"/>'; } else { svgEl.innerHTML = '<path fill="#AD28EB" d="M15 3.313A12.187 12.187 0 1 0 27.188 15.5 12.203 12.203 0 0 0 15 3.312Zm4.688 13.124h-3.75v3.75a.938.938 0 0 1-1.876 0v-3.75h-3.75a.938.938 0 0 1 0-1.875h3.75v-3.75a.938.938 0 0 1 1.876 0v3.75h3.75a.938.938 0 0 1 0 1.876Z"/>'; } } // Add a click event listener to each question box, calling the toggleAnswer function questionBoxes.forEach((qbox) => { qbox.addEventListener('click', () => toggleAnswer(qbox)); });
Improvements:
-
Reduced Repetition:
- A single function
toggleAnswer
now handles the toggling logic, reducing repetition.
- A single function
-
Parameterized Function:
- The
toggleAnswer
function now takes the specific box as a parameter, making it more flexible.
- The
-
Consistent Variable Naming:
- Variables have been renamed for consistency and clarity.
Best regards!
Marked as helpful1@Matt971xPosted 10 months ago@aykinsancakli Thank you very much for your comment, and the time you took to explain things clearly. I will try to work on it !
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