0
MathJax.Hub.Register.StartupHook("End", function() {

var classes = ["45e5d940-d015-4074-a934-f51ab8d6056a", "26ccb022-d472-4466-8c63-801e549ffcf2", "c4ecd641-e4e1-40a0-9560-fd4dc4d299b6", "d5d15822-f90d-4686-b816-77d8d4f28cc91Left", "d5d15822-f90d-4686-b816-77d8d4f28cc92Right", "a25b8ba9-03de-4068-b587-2b3c85380c591Left", "a25b8ba9-03de-4068-b587-2b3c85380c592Left", "a25b8ba9-03de-4068-b587-2b3c85380c593Right", "dd080c5f-3c94-4c04-bf59-68b03c8b75231Left", "dd080c5f-3c94-4c04-bf59-68b03c8b75232Left", "dd080c5f-3c94-4c04-bf59-68b03c8b75233Right", "d975febc-0e4f-46cc-b427-7989a2cbb0cb1Left", "d975febc-0e4f-46cc-b427-7989a2cbb0cb2Left", "d975febc-0e4f-46cc-b427-7989a2cbb0cb3Right", "32d6ac0d-6201-4045-8aca-a7cd086dd96a1Left", "32d6ac0d-6201-4045-8aca-a7cd086dd96a2Left", "32d6ac0d-6201-4045-8aca-a7cd086dd96a3Right", "1e89393b-8ff4-40c6-855b-812b7ee6f1ed1Left", "1e89393b-8ff4-40c6-855b-812b7ee6f1ed2Left", "1e89393b-8ff4-40c6-855b-812b7ee6f1ed3Right"];
for (var i = 0; i < classes.length; i++) {
    console.log(i); // this prints correctly every loop
    console.log(classes[i]); // this prints correctly every loop
    console.log(document.getElementById(classes[i] + "_event")); // this finds it correctly
    var c = classes[i];
    document.getElementById(c + "_event").addEventListener("mouseover", function() {
        var classList = document.getElementsByClassName(c);
        console.log(c); // prints the last item in the classes list every time -- bug
        console.log(classList);
        Array.from(classList).forEach(function(e) {
            if (e["style"]) {
                e.style["color"] = "red";
            }
        });
    });
}
});

This code has a scope problem. The variable 'c' is defined in the for loop referring to the index of the item in the loop.

I can correctly connect the event up but the function that gets called from the event has the c variable defined as the last item in the list when called.

If I replace c with classes[i] it will print undefined (when in the function)

John Smith
  • 347
  • 1
  • 11

0 Answers0