0

Running a for loop to create a number of divs with ID at1, at2, at3, etc.

    function maketiles() {
        for (i = 1; i < 7; i++) {
            var div = document.createElement('div');
            div.id = "at" + i;
            $("tiles").appendChild(div);
        }
    }

Then I addEventListener to each div so they can be clicked to call another function and pass a unique number (same number as their ID) to said function.

If I add them separately like this:

        $("at1").addEventListener("click", function () { build(1) });
        $("at2").addEventListener("click", function () { build(2) });
        $("at3").addEventListener("click", function () { build(3) });
        $("at4").addEventListener("click", function () { build(4) });
        $("at5").addEventListener("click", function () { build(5) });
        $("at6").addEventListener("click", function () { build(6) });

It works fine. But it would be more efficient to just add that one line during the loop, like this:

    function maketiles() {
        for (i = 1; i < 7; i++) {
            var div = document.createElement('div');
            div.id = "at" + i;
            $("altartiles").appendChild(div);
            $(div.id).addEventListener("click", function () { build(i) });
        }

Yet that doesn't work. It seems that the problem is the i variable. It doesn't turn into the 1, 2, 3.. that it contains. Is there any way to make this work?

PS In case it wasn't clear, I have

    var $ = function (id) { return document.getElementById(id); };

set, just like jquery.

  • You could simply use the reference of the div add the event listener directly on the div. like. `div.addEventListener` – Sohail Ashraf Jan 19 '21 at 02:19
  • That doesn't work though. I tried it. Again the problem is with passing the variable from the loop into the function I want to add on with addEventListener.. – Jack Chandelier Jan 19 '21 at 03:55
  • Looks like it was an issue of scope, from reusing the i variable in multiple loops. Changing i = 1 to let i = 1 made it work. – Jack Chandelier Jan 19 '21 at 04:04

0 Answers0