@piushbhandari
Posted
- use
.questions:last-child{}
to remove the border + bottom margin/padding from the last question - any reason why
<div class="question">
isn't a button element? right now i can't use your component with my keyboard. using semantic elements is always a good thing. there are more accessible things you can do but replacing it with a button element is a good start - assign classes instead of setting inline styles. i.e add active to the answer and give it
display:flex;
- if this
<div class="title">
is being used as your main title replace the the div with <h1>
Marked as helpful
@SebBudynski
Posted
Hello @piushbhandari ! Thank you for all advices. I made corrections right away but one i didn't understand. Can you tell me more about : assign classes instead of setting inline styles. i.e add active to the answer and give it display:flex; ?
Regards Sebastian
@piushbhandari
Posted
@SebBudynski
so for example, what you would do is, in your css, have a class like so .active { display: block; }
instead of doing this in javascript, for example, element.style.display='block';
you can instead do this:
when the accordion question button is clicked/opened, add the .active class to the button + content. then when you click on it again, remove the .active class. about the same thing what you're doing currently but instead using css classes to hide/show the accordions.
you would be adding/removing the .active class on both your .question button element and .answer paragraph element. likely you may need to update your styles
example code of what i did in my project:
if (accordionBtn.classList.contains("active")) {
accordionBtn.classList.remove('active');
}
else if (!accordionBtn.classList.contains("active")) {
accordionBtn.classList.add('active');
}
you can see my JS to get a better understanding. hope this helps https://github.com/piushbhandari/faqaccordion/blob/main/script.js
Marked as helpful
@SebBudynski
Posted
@piushbhandari
Your solution help me understand how exactly my code is working. Now I see that creating a class in css and toggling it does a great job:
const acc = document.getElementsByClassName("question");
let i;
for (i = 0; i < acc.length; i++) { acc[i].addEventListener("click", function () { this.classList.toggle("active");
let hidden = this.nextElementSibling;
hidden.classList.toggle("hidden");
}); }
Thanks for looking in my code, it's help me a lot.