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:
- Select a file.
- Some checks, get the HTML code from a template, add a line to the files list.
- 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:
Line from template:
line = line_template_code .replace(/{{subidor_nombre}}/g, fic.name) .replace(/{{id_fichero}}/g, fic.id);Inserting of line:
document.getElementById('files_list').innerHTML += line;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;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:
As seen, there's only one file in the list. The button on the file line has its event handler attached:
If a second file is added, it gets its event handler, whereas former file button loses event handler:
Moreover, doesn't matter if I add any text, not just HTML.