Skip to content

Instantly share code, notes, and snippets.

@KGDewey
Created February 5, 2025 23:51
Sliding FAQ's 3
<script>
document.addEventListener('DOMContentLoaded', () => {
const faqQuestions = document.querySelectorAll('.faq-question');
faqQuestions.forEach((question) => {
question.addEventListener('click', (e) => {
const faqItem = e.target.parentElement;
const faqAnswer = faqItem.querySelector('.faq-answer');
// Close all other open answers and questions
document.querySelectorAll('.faq-answer').forEach((answer) => {
if (answer !== faqAnswer) {
answer.style.maxHeight = null;
answer.classList.remove('open');
answer.previousElementSibling.classList.remove('open');
}
});
// Toggle the clicked answer and question
if (faqAnswer.style.maxHeight) {
faqAnswer.style.maxHeight = null;
faqAnswer.classList.remove('open');
e.target.classList.remove('open');
} else {
faqAnswer.style.maxHeight = `${faqAnswer.scrollHeight + 20}px`;
faqAnswer.classList.add('open');
e.target.classList.add('open');
}
});
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment