HTML
I'm looking to add a FAQ question within the div with the class "section-center"
<body>
<section class="questions">
<div class="title">
<h2>FAQ SECTION</h2>
</div>
<div class="section-center">
<!-- dynamic data insert here -->
</div>
</section>
<!-- script -->
<script src="/script.js"></script>
</body>
</html>
CSS
With the use of JavaScript, we will be able to add or remove the "show-text" class. When the "show-text" class is added, the 'question-text' class will display block (making the answer visible), the 'minus-icon' class will display inline (revealing the minus icon which was initially hidden), and the 'plus-icon' class will have display none (the plus icon disappears).
.question-text {
display: none;
}
.show-text .question-text {
display: block;
}
.minus-icon {
display: none;
}
.show-text .minus-icon {
display: inline;
}
.show-text .plus-icon {
display: none;
}
JS
This array holds questions and answers
const faq = [
{
ques: 'this is test question',
answer: 'this is test answer ',
},
{
ques: 'this is test question',
answer: 'this is test answer ',
},
]
We are traversing the DOM in order to insert the question/answer where needed.
const sectionCenter = document.querySelector('.section-center');
The function displayQuestion is called when the webpage loads to show the question and answer.
window.addEventListener('DOMContentLoaded', () => {
displayQuestions(faq);
});
const questions = document.querySelectorAll('.question');
//console.log(questions);
This portion of code enables the feature of automatically closing an open question when another question is opened by clicking on a toggle button.
questions.forEach((question) => {
const btn = question.querySelector('.question-btn');
btn.addEventListener('click', () => {
questions.forEach((curQuestion) => {
if (curQuestion !== question) {
curQuestion.classList.remove('show-text');
}
});
question.classList.toggle('show-text');
});
});
A function to display question and answer
// function to display questions
function displayQuestions(items) {
let display = items.map(({ ques, answer }) => {
return `
<article class="question">
<div class="question-title">
<P>${ques}</P>
<button type="button" class="question-btn">
<span class="plus-icon">
<i class="far fa-plus-square"></i>
</span>
<span class="minus-icon">
<i class="far fa-minus-square"></i>
</span>
</button>
</div>
<div class="question-text">
<p>${answer}</p>
</div>
</article>
`;
});
display = display.join('');
// console.log(display);
sectionCenter.innerHTML = display;
}