Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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\"/>"
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading