0

I am using JS to create a simple table, every row with 2 or 3 cells. I also add an EventListener to the first cell on each row. But it works only on red highlighted cells. Can you tell me why? Thanks

Table with highlighted cells]

function vytvoritTabulku(table, data, mapa) {
    let thead = table.createTHead();
    let row = thead.insertRow();
    let th = document.createElement("th");
    let text = document.createTextNode("Název DTS Stanice");

    th.appendChild(text);
    row.appendChild(th);
    console.log(data.length);

    for (let i = 0; i < data.length; i++){
        let row = table.insertRow();


        let cell = row.insertCell();
        let text = document.createTextNode(data[i].nazev);
        cell.appendChild(text);

        cell.bgColor = "yellow";

        cell.addEventListener("click", () => {
            if (data[i].visible){
                data[i].marker.removeFrom(map);
                //stanice[0].trasaDo.removeFrom(map);
                data[i].trasaZ.removeFrom(map);
                data[i].visible = false;
                console.log("Skryvam");
                cell.bgColor = "Red";
            } else {
                data[i].marker.addTo(map);
                //stanice[0].trasaDo.removeFrom(map);
                data[i].trasaZ.addTo(map);
                data[i].visible = true;
                console.log("Zobrazuji"); 
                cell.bgColor = "yellow";
            }
        });

        let cell2 = row.insertCell();
        text = document.createTextNode("There will be a button");
        cell2.appendChild(text);
    }
 
  }

I tried to define the handler method outside but it was the same. I also tried to change let i in for cycle to i = 14 but then eventListener doesnt work on every cell.

Smaller table from let i = 14, doesnt work

  • what does `console.log(data.length);` output? – GrafiCode Oct 25 '22 at 19:09
  • Use [event delegation](//developer.mozilla.org/en/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of adding several listeners — it’s more maintainable and applies to dynamically added elements. See [the tag info](/tags/event-delegation/info) and [this Q&A](/q/1687296/4642212). Use the [event argument](//developer.mozilla.org/en/docs/Web/API/EventTarget/addEventListener#The_event_listener_callback): `table.addEventListener("click", ({`[`target`](//developer.mozilla.org/en/docs/Web/API/Event/target)`}) => { const td = target.closest("td:first-of-type"); if(td){`…`} });`. – Sebastian Simon Oct 25 '22 at 19:09
  • @GrafiCode Its just information of lenght of an array – Petr Klíma Oct 25 '22 at 19:20
  • @SebastianSimon I tried to use event argument you mentioned but it still works only on half of table – Petr Klíma Oct 25 '22 at 19:21

0 Answers0