ADOBE AFTER EFFECTS: Forum Expressions Tutorials Creative Cloud

attaching onClick events to checkboxes with for loop

COW Forums : Adobe After Effects Expressions

<< PREVIOUS   •   FAQ   •   VIEW ALL   •   PRINT   •   NEXT >>
Goran Hanzek
attaching onClick events to checkboxes with for loop
on Feb 8, 2020 at 1:32:44 pm

I have a problem with attaching onClick events to checkboxes.
I wan't to control light layers using interface. First I collect all lights in array, and then I create UI/pallette with checkboxes for turning lights on/off.
If I do it manually (hard coding) everything works as expected. Here is the example:

checkbox[0].onClick = function() {
light[0].enabled = !light[0].enabled;

Checkbox is array of checkboxes (how many lights that many checkboxes), and light is array of all lights in the composition. This works, but the problem is if you have more lights (and you don't know when scripting how many lights are going to be in the composition).
Possible solution was to attach onClick event to every checkbox using for loop, like this:

for(i=0; i<light.length; i++){
checkbox[i].onClick = function() {
light[i].enabled = !light[i].enabled;

But the problem is that counter i does not work in the function. After executing the script, and trying to turn on/off lights, function is still using i number (which is number of lights + 1). So in the end, what I get is this (simulation for a scene with 2 lights - counter should be 0 or 1, depending which light you try to turn on/off):

checkbox[2].onClick = function() {
light[2].enabled = !light[2].enabled;

This line of code executes for light1 and also for light 2. And no matter how many lights, number is allways number of lights +1.

What am I missing? How come the script works fine when hard coding numbers but it does not when using for loop. Does i counter even enter the function. It seems that instead of actual number, the variable i is used when trying to turn lights on/off.


Return to posts index

Andrei Popa
Re: attaching onClick events to checkboxes with for loop
on Feb 10, 2020 at 7:10:28 am

I am not sure if this would work, but maybe something like i = this.index; inside the function. Or if you name your checkboxes Light 1, Light 2 etc, you can use this:
i = parseInt(this.text.split(" ")[1]);

My Envato portfolio.

Return to posts index

Goran Hanzek
Re: attaching onClick events to checkboxes with for loop
on Feb 10, 2020 at 10:08:10 am

It works perfectly with second solution.

Thanks Andrei!

Return to posts index

<< PREVIOUS   •   VIEW ALL   •   PRINT   •   NEXT >>
© 2020 All Rights Reserved