title: How to define javascript event handlers dynamically with a function
body: <p>I'm somewhat new to Javascript and I can't seem to figure out exactly what's going on with my functions.  </p>
  
  <p>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)</p>
  
  <p>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:</p>
  
  <pre><code>  function makeToggle () {
      for (i=0;i&lt;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";
      }
    }
  </code></pre>
  
  <p>"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:</p>
  
  <pre><code>onclick="toggleSection(this,0)"
  onclick="toggleSection(this,1)"
  </code></pre>
  
  <p>What they are actually set for (assuming I have 5 elements defined as a toggler) is:</p>
  
  <pre><code>onclick="toggleSection(this,5)"
  onclick="toggleSection(this,5)"
  </code></pre>
  
  <p>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</p>