I wasn't sure how to write that question logically, I pretty much figured the togglw out, but I struggle with something else. When I click on one element and open it, I want to click on another one to open and the previously opened to close. It doesn't work, however. Whenever I click on another element, the opened one just closes without opening the other. Basically, I want to close the element only when I click on that specific element. Or when I click on another one (which kinda works) but in this case also want the other to open, if that makes sense. I am stuck at this point.
Thanks for any help.
Here is my codepen: https://codepen.io/danosvk/pen/JjLEGMK
Here is my code:
const questions = document.querySelectorAll("section");
const answers = document.querySelectorAll(".answer");
toggle = false
function open() {
for (let i = 0; i < answers.length; i++) {
answers[i].style.display = "none";
}
toggle = !toggle
this.lastElementChild.style.display = toggle ? "block" : "none"
}
questions.forEach((question) => question.addEventListener("click", open));
.card {
width: 20.4375rem;
background-color: #ffffff;
border-radius: 1.4375rem;
margin: auto;
padding: 132px 24px 48px;
text-align: center;
transform: translateY(-125px);
}
section {
display: flex;
align-items: center;
justify-content: space-between;
border-bottom: 1px solid #e8e8ea;
flex-wrap: wrap;
}
p {
color: var(--main-text-color);
font-size: 0.75rem;
}
.answer {
flex-basis: 100%;
text-align: left;
display: none;
}
<div class="card">
<h1 class="no">faq</h1>
<section>
<p class="question">How many team members can i invite?</p>
<img class="arrow" src="./images/icon-arrow-down.svg" alt="" />
<p class="answer">
You can invite up to 2 additional users on the Free plan. There is no
limit on team members for the Premium plan.
</p>
</section>
<section>
<p class="question">What is the maximum file upload size?</p>
<img class="arrow" src="./images/icon-arrow-down.svg" alt="" />
<p class="answer">
No more than 2GB. All files in your account must fit your allotted
storage space.
</p>
</section>
<section>
<p class="question">How do I reset my password?</p>
<img class="arrow" src="./images/icon-arrow-down.svg" alt="" />
<p class="answer">
Click “Forgot password” from the login page or “Change password” from
your profile page. A reset link will be emailed to you.
</p>
</section>
<section>
<p class="question">Can I cancel my subscription?</p>
<img class="arrow" src="./images/icon-arrow-down.svg" alt="" />
<p class="answer">
Yes! Send us a message and we’ll process your request no questions
asked.
</p>
</section>
<section>
<p class="question">Do you provide additional support?</p>
<img class="arrow" src="./images/icon-arrow-down.svg" alt="" />
<p class="answer">
Chat and email support is available 24/7. Phone lines are open during
normal business hours.
</p>
</section>