Home > Enterprise >  How can I make the eventListener work in a table if there is an image inside it?
How can I make the eventListener work in a table if there is an image inside it?

Time:10-21

I have a simple table, and my task is to put an image in the table cells when clicking, or to remove them if there is already an image inside. My code is the following:

const table = document.querySelector("tbody")
table.addEventListener("click", clickTile)

function clickTile(e){
    if(e.target.matches("td")){
        const row = e.target.closest("tr").rowIndex
        const col = e.target.closest("td").cellIndex
        placeImage(row, col)
    }
}

function placeImage(row, col){
    const cell = table.rows[row].cells[col]
    if(cell.innerHTML != ""){
        cell.innerHTML= ""
        return
    }
    
    cell.innerHTML = "<img src=\"image.png\" height=\"20px\" width=\"20px\"/>"
}

It doesn't work if I click directly on the image, only if I click somewhere where I'm still inside the cell, but not on the image.

CodePudding user response:

Use Element.closest() as well in the if statement to capture the td element and all of its descendents.

Then query for the image in the cell, remove if it is there, or add it if it isn't.

function clickTile(e) {
  const td = e.target.closest("td");

  if (target.closest("td")) {
    const row = e.target.closest("tr").rowIndex;
    const col = td.cellIndex;
    const image = td.querySelector('img');

    if (image === null) {
      placeImage(row, col);
    } else {
      removeImage(image);
    }
  }
}

function removeImage(image) {
  image.remove();
}

function placeImage(row, col){
  const cell = table.rows[row].cells[col]
  cell.innerHTML = "<img src=\"image.png\" height=\"20px\" width=\"20px\"/>"
}
  • Related