title: Sorting tables Javascript
body: <p>I'm sorting a table when a user clicks on the table head, and I'm using vanilla Javascript to do this. I'm trying to capture the column number by clicking the <code>&lt;th&gt;</code> table head and pass it to the <code>sortTable(n)</code> function. Also, I'm trying to start the <code>sortTable(n)</code> function after column data is captured. I'm not sure where my error is at?</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>document.getElementById('myTable2').addEventListener('click', function() {
    myFunction(event)
  }, true);
  
  function myFunction() {
    var col = window.event.target.cellIndex;
    var n = col;
    sortTable(n);
    return n;
  
  }
  
  function sortTable(n) {
    var n = myFunction();
    var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
    table = document.getElementById("myTable2");
    switching = true;
    
    dir = "asc";
    while (switching) {
     switching = false;
      rows = table.rows;
      /* Loop through all table rows (except the
      first, which contains table headers): */
      for (i = 1; i &lt; (rows.length - 1); i++) {
        // Start by saying there should be no switching:
        shouldSwitch = false;
        /* Get the two elements you want to compare,
        one from current row and one from the next: */
        x = rows[i].getElementsByTagName("TD")[n];
        y = rows[i + 1].getElementsByTagName("TD")[n];
        /* Check if the two rows should switch place,
        based on the direction, asc or desc: */
        if (dir === "asc") {
          if (x.textContenttextContent.toLowerCase() &gt; y.textContent.toLowerCase()) {
            shouldSwitch = true;
            break;
          }
        } else if (dir === "desc") {
          if (x.textContent.toLowerCase() &lt; y.textContent.toLowerCase()) {
            // If so, mark as a switch and break the loop:
            shouldSwitch = true;
            break;
          }
        }
      }
      if (shouldSwitch) {
        rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
        switching = true;
        // Each time a switch is done, increase this count by 1:
        switchcount++;
      } else {
         if (switchcount === 0 &amp;&amp; dir === "asc") {
          dir = "desc";
          switching = true;
        }
      }
    }
  }</code></pre>
  </div>
  </div>
  </p>