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

127
Views
JavaScript dynamicly added buttons lose event handler

I coded a JavaScript file uploader for my projects; nothing particularly fancy or complicated, I think. In the uploading interface files are added and presented in a list with an uploading button to which a click event handler is attached. The problem I've found is the event handler from previous buttons vanishes when adding a new file to the list; happens right after adding content to the files list, whether it's HTML or not, whether by appending it to innerHTML or by using createElement() and appendChild().

The process is as following:

  1. Select a file.
  2. Some checks, get the HTML code from a template, add a line to the files list.
  3. Get the HTML code for the file handling button, add the button to the file line, attach an event handler.

Here it is the code I use:

  1. Line from template:

    line = line_template_code  
        .replace(/{{subidor_nombre}}/g, fic.name)  
        .replace(/{{id_fichero}}/g, fic.id);
    
  2. Inserting of line:

    document.getElementById('files_list').innerHTML += line;
    
  3. DOM insertion of button for handling file upload:

    button = button_template_code.replace(/{{id_fichero}}/g, fic.id); document.getElementById('file_line_id').innerHTML += button;
    
  4. Attaching of event handler to button already added to DOM:

    document  
        .getElementById('button_id')  
        .addEventListener('click', e => {  
            file_hanling_function(file, hanling_url);  
        }, false);
    

Event handler of former buttons happens in step 2.

Here it is a screen capture of the form interface:

enter image description here

As seen, there's only one file in the list. The button on the file line has its event handler attached:

enter image description here

If a second file is added, it gets its event handler, whereas former file button loses event handler:

enter image description here

Moreover, doesn't matter if I add any text, not just HTML.

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!