How can I create a FAQ section on a page? I want to ask 5-6 questions and have the answers below. Is there ready-made code for creating create a FAQ section or suggest a ready-made template that has one?
The Bootstrap accordion component is perfect for creating FAQs. Here’s one I created which I shared in the online library.
Go to the online library and search for Ultimate Accordion with arrow icon
Note: The component in the library does not include the JS that makes the accordion scroll automatically to the currently selected question, like it does on the website. For that, you need to create some JavaScript…
const accordionItems = document.querySelectorAll('.accordion-collapse');
function scrollToAccordionItem() {
let offset = window.innerWidth >= 768 ? 204 : 69;
let accordionItem = this.closest('.accordion-item');
window.scrollTo({
top: accordionItem.offsetTop - offset,
left: 0,
behavior: 'smooth'
});
}
accordionItems.forEach((el) => {
el.addEventListener('shown.bs.collapse', scrollToAccordionItem);
});
function resizeHandler() {
let offset = window.innerWidth >= 768 ? 204 : 69;
let activeAccordionItem = document.querySelector('.accordion-item.show');
if (activeAccordionItem) {
window.scrollTo({
top: activeAccordionItem.offsetTop - offset,
left: 0,
behavior: 'smooth'
});
}
}
window.addEventListener('resize', resizeHandler);
This line is how you set the height from the top (depending on screen size)…
let offset = window.innerWidth >= 768 ? 204 : 69;
The accordion will work fine without the JS. It’s just a nice addition.
3 Likes