0

I'm trying to make a file explorer on a website. In first, I'm making an XMLHttpRequest to get all file in the current repertory and add it to the HTML. The problem is when I want to put an event Listener on all nodes I got in the HTML he can't because the XML request always finishes after the moment where I would like to put the event Listener...

$(window).on("load", function() {
    //prépare ajax
    let ajax = new XMLHttpRequest();
    let methode = "GET";
    let url = "php/getFile.php"
    let asynchronous = true;
    ajax.open(methode, url, asynchronous);

    ajax.send();
    let data;
    ajax.onreadystatechange = function() {

        if (this.readyState == 4 && this.status == 200) {
            let data = JSON.parse(this.responseText);
            let files = ` <ul data-role="listview" data-view="list" data-select-node="true">
            <ListView ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollMode="Enabled" >`;
            for (let i = 0; i < data.length; i++) {
                let file = data[i];
                let nom = file['file'];
                let ext = "." + file['ext'];
                let nudeExt = file['ext'];

            files += `<li id="test" data-icon="<span class='mif-document-file-${nudeExt.toLowerCase()}'>" data-caption="${nom}"></li>`
                

            }
            files += `   </ul>`;
            document.querySelector("#files").innerHTML = files;
            
// I try to put the event listener here but it doesn't work,  

            document.querySelector("#test").addEventListener("onclick", test());
        }

    }


})

function test() {
    let test = document.querySelector('#test');
    console.log(test)
}

ANSWER

At the place of add an event listener like this :

document.querySelector("#test").addEventListener("onclick", test());

I have directly added the event in the node like this :

files += ` <li ondblclick="test()" class="folder" type="folder" data-icon="<span class='mif-folder'>" data-caption="${nom}"></li>

PascheK7
  • 11
  • 3
  • 2
    you are using the same `id` to every `
  • `, so you will have unexpected errors, since `id`s must be unique in the DOM.
  • – Calvin Nunes Nov 09 '21 at 18:46
  • Also `addEventListener("onclick", test())` is calling `test` and returning the result to the listener and, unless that's a function, that code isn't going to work. – Andy Nov 09 '21 at 18:49
  • Does this answer your question? [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – freedomn-m Nov 09 '21 at 18:49
  • Should be `.addEventListener("onclick", test);` if above comment wasn't clear enough – freedomn-m Nov 09 '21 at 18:56
  • @Andy If I put my event directly in the`
  • ` like `
  • ` that should work ? – PascheK7 Nov 09 '21 at 19:18