I'm somewhat new to Javascript and I can't seem to figure out exactly what's going on with my functions.
Background: my script is supposed to let you assign a class of either "toggler" or "toggled" to an element to have them automatically linked, so checking/unchecking the toggler will show/hide the toggled (I know there are many libraries that can do this but unfortunately I can't use them in this case)
The script executes on pageload and searches through the elements for ones with the class "toggler" and then assigns its onclick handler accordingly. Here's the bit of code I'm having problems with:
function makeToggle () {
for (i=0;i<toggler.length;i++) {
toggler[i].onclick=function(){toggleSection(this,i)};
}
}
function toggleSection(obj,index) {
if (obj.checked==true) {
toggled[index].style.display="inline-block";
} else {
toggled[index].style.display="none";
}
}
"This" is passed correctly and resolves to whatever checkbox it's applied to, but "index" is always set to the length of the toggler array instead of being incremented. For example, the first and second togglers' onclick should be:
onclick="toggleSection(this,0)"
onclick="toggleSection(this,1)"
What they are actually set for (assuming I have 5 elements defined as a toggler) is:
onclick="toggleSection(this,5)"
onclick="toggleSection(this,5)"
From what I've read I think it's a scoping problem, or the way I'm calling the function, but nothing I've found makes much sense