Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

103
Views
Injected event listeners in Vue JS project don't always fire on page change

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!