0

new to javascript. What i want this program to do is if the first cell of each row is clicked, I want to highlight that row. If any other cell is clicked, I want to highlight that one cell. I think my logic is correct, if I can get the cell index, I can highlight the correct cell(s) but the number that keeps getting passed into my highlight function is 9. Not sure where I'm going wrong.

window.onload = function() {
  var cells = document.getElementsByTagName("td");
  var theads = document.getElementsByTagName("th");

  for (var i = 0; i < cells.length; i++) {
    cells[i].addEventListener("click", function() {
      highlightCell(i);
    });
  }

    function highlightCell(x) {
      //alert(x + " clicked");
      if (x == 0) {
        //highlight table cells 0,1,2 lightBlue
        //highlight others to white
      } else if (x == 3) {
        //highlight table cells 3,4,5
        //highlight others to white
      } else if (x == 6) {
        //highlight table cell 6,7,8
        //highlight others to white
      } else {
        //highlightCell single table cell clicked
        //hihglight others to white
      }
    }

  }
}
user3826764
  • 198
  • 1
  • 9

3 Answers3

0

Change var i to let i. let addresses a Javascript problem with references and closures. Reference: https://stackoverflow.com/a/30479554/5351510

for (let i = 0; i < cells.length; i++) {
  cells[i].addEventListener("click", function() {       
    highlightCell(i);
  });
}
Wild Beard
  • 2,919
  • 1
  • 12
  • 24
Gordon Kushner
  • 165
  • 1
  • 9
0

Gordon's answer will work, but let is an addition to the standards that may not be supported in all browsers. You can rewrite your functionality like this for closure and broader compatibility:

var cells = document.getElementsByTagName("td");
var theads = document.getElementsByTagName("th");

for (var i = 0; i < cells.length; i++) {
  (function(){
    var x=i
    cells[x].addEventListener("click", function() {
      highlightCell(x);
  }());
}

function highlightCell(x){
  console.log(x);
}
Anthony L
  • 2,159
  • 13
  • 25
0

This is a typical scope problem that can be solved with a closure. Basically the variable i in your 'for' is accessing the i value of the outer scope which is the last number the i got from the 'for'. To solve this you need to bind the variable within each function to a separate unique scope so it doesn't access the outer scope.

Check this guide to scopes and closures: https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch1.md.

return a function that returns your function so you create a new scope.

function highlightCell(i) {
  return function() { ...do your highlight thing that uses i... };
}

cells[i].addEventListener("click", function() {
  highlightCell(i);
});
Ignacio
  • 1,056
  • 8
  • 17