JSFiddle - React, Tailwind, and code Playground
HTML
<div class="submitSOBox">
</div>
<div class="submitSOBox">
</div>
<div class="submitSOBox">
</div>
<div class="submitSOBox">
</div>
CSS
.submitSOBox {
width: 100px;
height: 100px;
background: red;
margin-bottom: 10px;
}
JavaScript
var submitSOBox = document.getElementsByClassName("submitSOBox");
//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 (remove this code to see the issue)
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";
}