So I am using Flowbite and vanilla JavaScript to do a UI.
I am dynamically adding items to an accordion by loading them (via PHP) from a DB. So the PHP script returns an id, section name and section text as JSON.
Now this script then generates the HTML to fit in the accordion container:
document.addEventListener('DOMContentLoaded', function() {
fetch('src/php/getExecSummary.php')
.then(response => response.json())
.then(data => {
const accordionContainer = document.getElementById('accordionExecSummary');
data.forEach((section, index) => {
const isOpen = index === 0 ? true : false;
const sectionElement = `
<h2 id="accordion-heading-${index}">
<button type="button" data-accordion-target="#accordion-collapse-body-${index}" class="flex items-center justify-between w-full p-5 font-medium text-left border-b border-gray-200" aria-expanded="${isOpen}" aria-controls="accordion-collapse-body-${index}">
<span>${section.SectionName}</span>
<!-- Include accordion icon here -->
</button>
</h2>
<div id="accordion-collapse-body-${index}" class="${isOpen ? '' : 'hidden'}" aria-labelledby="accordion-heading-${index}">
<div class="p-5 border-b border-gray-200">
<textarea class="w-full h-32 p-2 border border-gray-300">${section.SectionText}</textarea>
</div>
</div>
`;
accordionContainer.innerHTML += sectionElement;
});
})
.catch(error => console.error('Error loading executive summary sections:', error));
});
So I get the sections and the sections are named from data back from the DB but I cannot interact with the accordion; so clicking the section name doesn't expand/collapse the section. No errors in the console and cant find any refresh() method or anything like that.
Not sure what else I can do?
As per the documentation:
As per the example, we need to build the list of
itemsthat are the accordions within the accordion group. We can turn the.forEach()into a map like so:It is important to replace the
.innerHTMLassignment with the above.insertAdjaccentHTML()call. This is because.innerHTMLassignment causes the entire inner HTML of the container to be reparsed, meaning that previous JavaScript object representations don't actually refer to their elements anymore, whereas.insertAdjaccentHTML()prevents this from happening.After this, initialize a new
Accordionobject from Flowbite:Full example: