I'm working with a Nuxt JS / Vue JS app with dynamic pages. My pages fetch data from a remote api which includes HTML and JS that needs to be executed.
In my context, I have a bunch of accordions, that when tapped should open the contents, so in the then block of my axios request I'm creating a script tag on the page with the contents:
const string = "some JS from api"
const injectTo = document.querySelector('[data-beam-injectes-interactivity]')
const script = document.createElement('script')
script.innerHTML = string
injectTo.appendChild(script)
The string of JS injected is:
function initDeviceGroupCollapses () {
const buttons = document.querySelectorAll('[data-toggle="collapse"]')
if (buttons) {
for (const [index, button] of buttons.entries()) {
if (button) {
button.addEventListener('click', (event) => {
event.stopPropagation()
const target = event.target.dataset.target
if (!target) {
return
}
const collapse = document.querySelector(target)
collapse.style.display = collapse.style.display == 'none' ? 'block' : 'none'
}, false)
}
}
}
}
The issue I'm having though is that if the JS is injected into a page where the HTML doesn't initially exist, the event listeners no longer fire on data-toggle="collapse".
How can I always make sure that the injected JS works?