title: Javascript multiple dynamic addEventListener created in for loop - passing parameters not working
body: <p>I want to use event listeners to prevent event bubbling on a div inside a div with onclick functions. This works, passing parameters how I intended:</p>
  
  <pre><code>&lt;div onclick="doMouseClick(0, 'Dog', 'Cat');" id="button_id_0"&gt;&lt;/div&gt;
  &lt;div onclick="doMouseClick(1, 'Dog', 'Cat');" id="button_id_1"&gt;&lt;/div&gt;
  &lt;div onclick="doMouseClick(2, 'Dog', 'Cat');" id="button_id_2"&gt;&lt;/div&gt;
  
  &lt;script&gt;
  function doMouseClick(peram1, peram2, peram3){
      alert("doMouseClick() called AND peram1 = "+peram1+" AND peram2 = "+peram2+" AND peram3 = "+peram3);
  }
  &lt;/script&gt;
  </code></pre>
  
  <p>However, I tried to create multiple event listeners in a loop with this:</p>
  
  <pre><code>&lt;div id="button_id_0"&gt;&lt;/div&gt;
  &lt;div id="button_id_1"&gt;&lt;/div&gt;
  &lt;div id="button_id_2"&gt;&lt;/div&gt;
  
  &lt;script&gt;
  function doMouseClick(peram1, peram2, peram3){
      alert("doMouseClick() called AND peram1 = "+peram1+" AND peram2 = "+peram2+" AND peram3 = "+peram3);
  }
  
  var names = ['button_id_0', 'button_id_1', 'button_id_2'];
  
      for (var i=0; i&lt;names.length; i++){
  
          document.getElementById(names[i]).addEventListener("click", function(){
          doMouseClick(i, "Dog", "Cat");
  
      },false);
  
  }
  
  &lt;/script&gt;
  </code></pre>
  
  <p>It correctly assigns the click function to each div, but the first parameter for each, <code>peram1</code>, is <code>3</code>. I was expecting 3 different event handlers all passing different values of <code>i</code> for <code>peram1</code>.</p>
  
  <p>Why is this happening? Are the event handlers not all separate?</p>