Hi, good job and very nice accordion.
I played little bit with your js code and reduced it to 1 loop.
this is how i did it with 3 steps.
Step 1:
first I needed to add to your css styles 2 new classes, so i could toggle the Dom styles with js:
.hide{
display: none;
}
.section-title.minus{
background: url(./images/icon-minus.svg) no-repeat center right;
}
Step 2.
HTML file i added .hide
class to all <p>
tags except the first because i want it to be open at firt load of the page. also Only to the first title added the .minus
class to show the minus icon because the text is also showen:
<section class="section-container">
<h2 class="section-title minus" tabindex="1">What is Frontend Mentor, and how will it help me?</h2>
<p class="section-text">Frontend Mentor offers realistic coding challenges to help developers improve their
frontend coding skills with projects in HTML, CSS, and JavaScript. It's suitable for
all levels and ideal for portfolio building.</p>
</section>
<section class="section-container">
<h2 class="section-title" tabindex="2">Is Frontend Mentor free?</h2>
<p class="section-text hide">Yes, Frontend Mentor offers both free and premium coding challenges, with the free
option providing access to a range of projects suitable for all skill levels.</p>
</section>
<section class="section-container">
<h2 class="section-title" tabindex="3">Can I use Frontend Mentor projects in my portfolio?</h2>
<p class="section-text hide">Yes, you can use projects completed on Frontend Mentor in your portfolio. It's an excellent
way to showcase your skills to potential employers!</p>
</section>
<section class="section-container">
<h2 class="section-title" tabindex="4">How can I get help if I'm stuck on a challenge?</h2>
<p class="section-text hide">The best place to get help is inside Frontend Mentor's Discord community. There's a help
channel where you can ask questions and seek support from other community members.</p>
</section>
Step 3.
I've used the classList.toggle()
js method to toggle between classes, and also used the same loop for the Keyboard event.
this is the reduced code:
const clickOnTitle = document.querySelectorAll('h2');
const sectionP = document.querySelectorAll('section p');
for(let i = 0; i < clickOnTitle.length; i++)
{
/*Mouse Event */
clickOnTitle[i].addEventListener('click', function () {
sectionP[i].classList.toggle('hide')
clickOnTitle[i].classList.toggle('minus')
})
/*Keyboard Event*/
clickOnTitle[i].addEventListener('keydown', event => {
if (event.key === 'Enter') {
sectionP[i].classList.toggle('hide')
clickOnTitle[i].classList.toggle('minus')
}
})
}
This code works well on my computer, didn't test it on mobile.
If you have any question Iet me know.
I hope you like my reduced code :)