0

I'm trying to create a for loop to shorten my code however when I test the code and try and make all the individual squares disappear when clicked, only the last one is disappearing and the others remain. I am quite stuck as the console is not giving me any errors either!

Please see my original long code targeting each individual square:

        document.getElementById("square1").onclick = function disappear() {

        document.getElementById("square1").style.visibility = "hidden";

    } 

        document.getElementById("square2").onclick = function disappear() {

        document.getElementById("square2").style.visibility = "hidden";

    }

        document.getElementById("square3").onclick = function disappear() {

        document.getElementById("square3").style.visibility = "hidden";

    }

        document.getElementById("square4").onclick = function disappear() {

        document.getElementById("square4").style.visibility = "hidden";

    }

        document.getElementById("square5").onclick = function disappear() {

        document.getElementById("square5").style.visibility = "hidden";

    }

        document.getElementById("square6").onclick = function disappear() {

        document.getElementById("square6").style.visibility = "hidden";

    }

And this is the for loop I created to try and shorten my code:

   for (var i = 1; i < 7; i++) {

       var squaresDis = document.getElementById("square" + i);

       document.addEventListener("click", function disappear() {

           squaresDis.style.visibility = "hidden";

       }

                                 )};
  • looks like one of your square#'s doesn't exist – brian Jul 24 '17 at 20:48
  • 1
    @torazaburo I don't think that duplicate is correct. Isn't this just a closure issue? – david Jul 24 '17 at 21:28
  • Change `document.addEventListener` to `squaresDis.addEventListener` and `squaresDis.style.visibility = "hidden";` to `this.style.visibility = "hidden";` – Ason Jul 24 '17 at 21:30
  • @david Yes it is, which is also what the dupe link have an answer too ... though this post have another problem, which I wrote in my previous comment (and a simply solution to the closure issue) – Ason Jul 24 '17 at 21:34
  • @LGSon He changed the dupe, it was referencing a question related to code running before elements were created. – david Jul 24 '17 at 21:36
  • @david Okay...missed that ... will check edit history next time :) – Ason Jul 24 '17 at 21:37
  • @LGSon and david. Thank you both for your help. Very kind of you! – Filip Zindovic Jul 24 '17 at 22:12

0 Answers0