title: Javascript: Adding ability to "select" rows of a table, calling an event listener with arguments
body: <p>I am just starting off teaching myself Javascript after learning some basics in a university class a year ago. For a web app I am supposed to write, I need to allow users to "select" rows of a table, preferably by clicking on them. I have a strong Python background and my approach probably reeks of GTK paradigms. I have a nagging fear that I'm "reinventing the wheel" somehow by trying to do this when there is a much more standard or accepted way, but like I said, don't know much Javascript yet. My Javascript code to try and do this is:</p>
  
  <pre><code>//Get list of rows in the table
  var table = document.getElementById("toppings");
  var rows = table.getElementsByTagName("tr");
  
  var selectedRow;
  
  //Row callback; reset the previously selected row and select the new one
  function SelectRow(row) {
      if (selectedRow !== undefined) {
          selectedRow.style.background = "#d8da3d";
      }
      selectedRow = row;
      selectedRow.style.background = "white";
  }
  
  //Attach this callback to all rows
  for (var i = 0; i &lt; rows.length; i++) {
      var idx = i;
      rows[idx].addEventListener("click", function(){SelectRow(rows[idx])});
  }
  </code></pre>
  
  <p>This apparently doesn't work because after the loop exits idx is equal to rows.length - 1 so the row argument in SelectRow is rows[rows.length - 1], which is always the last row; that is, <strong>the values of i are not "saved" as arguments to the event listener callback.</strong> How can I call an event listener with its own saved arguments? <a href="https://stackoverflow.com/questions/14044257/javascript-to-add-table-row-onclick-events">This thread</a> seems to give a way to do this with the onclick property, but I understand that this is deprecated and addEventListener (or some monstrous IE-compatible addEvent library) is now the "correct" way to do it.</p>