I'm trying to make an FAQ accordion and I want it to have two main features: 1- one question and answer can be seen at a time (I managed to do that) 2- if toggling on the open question it closes, and vice-versa (that's what i'm struggling with)
Here's a pen that has a small copy of what I've done on codepen: https://codepen.io/simokitkat/pen/yLEONpo?editors=0010
here is the html:
<div >
<h1>FAQ</h1>
<ul>
<li>
<div >
<h2>How many team members can I invite?</h2>
</div>
<p>You can invite up to 2 additional users on the Free plan. There is no limit on team members for the
Premium
plan.
</p>
</li>
<li>
<div >
<h2>What is the maximum file upload size?</h2>
</div>
<p>No more than 2GB. All files in your account must fit your allotted storage space.</p>
</li>
<li>
<div >
<h2>How do I reset my password?</h2>
</div>
<p>Click “Forgot password” from the login page or “Change password” from your profile page. A
reset link
will be
emailed to you.</p>
</li>
<li>
<div >
<h2>Can I cancel my subscription?</h2>
</div>
<p>Yes! Send us a message and we’ll process your request no questions asked.</p>
</li>
<li>
<div >
<h2>Do you provide additional support?</h2>
</div>
<p>Chat and email support is available 24/7. Phone lines are open during normal business hours.</p>
</li>
</ul>
</div>
here's the CSS
.text h1 {
font-weight: 700;
font-size: 2rem;
margin-bottom: 20px;
}
ul {
list-style: none;
}
ul>li {
padding: 10px 10px 10px 0;
border-bottom: 1px solid grey;
}
.question {
margin-bottom: 10px;
}
ul li h2 {
font-weight: 400;
font-size: 1rem;
cursor: pointer;
transition: 0.1s;
}
ul li img {
transition: 0.3s;
}
ul li h2:hover {
color: red;
font-weight: 700;
}
li p {
font-weight: 400;
height: 0;
overflow: hidden;
transition: 0.3s;
}
.active p {
height: 40px;
}
and that's the JS code:
let allquestions = document.querySelectorAll("li");
allquestions.forEach(function (question) {
question.addEventListener("click", function () {
allquestions.forEach(function (element) {
element.classList.remove("active");
});
this.classList.toggle("active");
});
});
CodePudding user response:
You can use html details
tag
const details = document.querySelectorAll("details");
details.forEach((el) => {
el.addEventListener("click", () => {
details.forEach((detail) => {
if (detail !== el) {
detail.removeAttribute("open");
}
});
});
});
<details>
<summary>How many team members can I invite?</summary>
<p>
You can invite up to 2 additional users on the Free plan. There is no limit on team members for the Premium plan.
</p>
</details>
<details>
<summary>How many team members can I invite?</summary>
<p>
You can invite up to 2 additional users on the Free plan. There is no limit on team members for the Premium plan.
</p>
</details>