dimanche 12 juin 2016

Newbie - Difficulties With For Loops and Closures [duplicate]

This question already has an answer here:

Goal: When one of the box is clicked, it would become blue and the rest of the boxes would go back to it's original properties. (check jsfiddle to see visual representation)

I believe I did something wrong in the closure... but can't pinpoint how it is wrong

Code:https://jsfiddle.net/sm1dwk69/14/

    //EXAMPLAR 1: THIS CODE DOES NOT WORK
                for (i = 0; i < submitSOBox.length; i++) {
                  submitSOBox[i].addEventListener('click', SOBoxColor(i));//invokes value of SOBoxColor, hence return function is added.
                }

                function SOBoxColor(i) {
                  return function() {
                    submitSOBox[i].style.backgroundColor = "red";//This code does not work for some reason...
                    console.log(this);
                    this.style.backgroundColor = "blue";
                  };
                }
//EXAMPLAR 2: THIS DOES WORK
                for (i = 0; i < submitSOBox.length; i++) {
                  submitSOBox[i].addEventListener('click', SOBoxColor);
                }
                function SOBoxColor(){
                    for(i = 0; i < submitSOBox.length; i++){
                     submitSOBox[i].style.backgroundColor = "red";
                  }
                  this.style.backgroundColor = "blue";
                }

Aucun commentaire:

Enregistrer un commentaire