Home > Software engineering >  Javascript onclick function, how to get it to repeat?
Javascript onclick function, how to get it to repeat?

Time:04-16

var table = document.querySelectorAll(".validcell")[0];
if (table) table.onclick = function (e) {
    var target = (e || window.event).target;
    if (target.tagName in { TD: 1, TH: 1 })
        target.setAttribute('style', 'background-color: #F00');
    setInterval(table, 50);
};

Trying to get this function to repeat whenever a cell on 10/10 table is clicked. Seems to stop after 1 cell, top left corner is selected. Any ideas?

CodePudding user response:

var table = document.querySelectorAll(".validcell");
       
table.forEach(cell => cell.onclick = onclickHandler)

function onclickHandler(e) { 

  var target = e.target;

    if (target.tagName in { TD: 1, TH: 1 })
    {
      target.setAttribute('style', 'background-color: #F00');
    }
    
};
td, th{
  padding:5px;
  border:1px solid black
}
<table>
  <tr>
    <th >Header1</th>
    <th >Header2</th>
    <th >Header3</th>
   <tr>
   <tr>
    <td >Dummy Text</td>
    <td >Dummy Text</td>
    <td >Dummy Text</td>
   <tr>
</table>

  • Related