Green geometric forms
Green geometric forms

Reputation: 13

javascript addEventListener in for loops uses last variable for event

here's my code

    <body>
        <div id = "elementbox">
        </div>
<script>
var container = document.getElementById("elementbox");
function item_select() {
alert("e");
var selected_element = document.getElementsByClassName("on");
selected_element.className = "off";
alert(selected_element);
}
for (var i = 0; i < 20; i++) {
    dive = document.createElement("div");
    dive.id = i+1;
    dive.className = "off";
    if (dive.id === 8) { dive.className = "on"}
    dive.innerHTML = "<p>E</p>;
    (function(i) {
        dive.addEventListener("click", function(i) {
        document.getElementById(i).className = "on";
        item_select();
        }, true)
    })(i);
container.appendChild(dive);

}

</script>

    </body>
</html>

As you can see my addEventListener uses the incremented variable (i) to change the className of a specific div, so when the event is called i is equal to 20. how can I avoid this ?

Upvotes: 0

Views: 60

Answers (1)

Halcyon
Halcyon

Reputation: 57709

No, I don't believe that is what is going on. You already have immediate-invocation to close the value of i.

I think the problem is that i is the event object:

(function(i) {
    dive.addEventListener("click", function(i) {
                                            ^-- i should not be here
        document.getElementById(i).className = "on";
        item_select();
    }, true)
})(i);

It seems your click handler sets the class on to the next <div>. Consider using dive.nextSibling. This avoids the need to use id and i. It's possible that more complex behaviour is required so maybe having the id is useful.

Upvotes: 3

Related Questions