2

I have an html file with the following script:

<script type="module" src="js/app.js"></script>

This is where I put my app logic with other imports. Inside this app.js file, I have a function called test();

function test() {
    console.log("aaa");
}

This function is called in an onclick event in an HTML span element appended dynamically using this code:

buildSideBar(technologies) {
    if(technologies.length > 0) {
        let spans = ``;
        const loader = document.getElementById('loader');
        const sidebar = document.getElementById('sidebar');
        for(const technology of technologies) {
            spans += `<span onclick="test()">${technology}</span>`;
        }
        loader.style.height = '0';
        loader.style.visibility = 'hidden';
        sidebar.innerHTML += spans;
        sidebar.classList.remove('hidden');
    }
}

The spans are added as intended, however, when I press them I get an error:

Uncaught ReferenceError: test is not defined
at HTMLSpanElement.onclick ((index):1)

What am I doing wrong here?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Amine
  • 1,396
  • 4
  • 15
  • 32
  • `test` is likely not a global, so the HTML element doesn't have visibility to it. – VLAZ Sep 27 '19 at 22:08
  • Why are you generating HTML that has an inline onclick at all? [Just attach the event listener to the element via JS.](https://stackoverflow.com/questions/6348494/addeventlistener-vs-onclick) – VLAZ Sep 27 '19 at 22:10
  • @VLAZ Attaching the event listener dynamically requires me to actually create DOM elements which is a lot of work for me right now, I'm trying to be as minimal as possible. – Amine Sep 27 '19 at 22:19
  • `technologies.map(technology => {var el = document.createElement("span"); el.textContent = technology; el.addEventListener(test); return el; }` – VLAZ Sep 27 '19 at 22:21
  • @VLAZ Thanks, as of my main answer, I've found the solution. – Amine Sep 27 '19 at 23:08

1 Answers1

3

The test() function wasn't visible outside of the module, the solution was to add it to the window object so it can be accessible.

window.test= test;

And as @VLAZ mentioned, there is also the solution to dynamically bind the spans to an onclick.

Amine
  • 1,396
  • 4
  • 15
  • 32