Aug 25, 2020
Per Djurner

Highlight table row when hovering over specific table cell

Highlighting a table row when hovering over it is easy, you just use the :hover CSS pseudo-class. But what if you only want to highlight the table row when you hover over a specific table cell? It's a little more difficult because you can't achieve it using just CSS, you have to throw in some JavaScript as well.

<style>
  .highlight {
    background: #e2e8f0;
  }
</style>
<table>
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Data 1</td>
      <td class="hoverable">Data 2</td>
      <td>Data 3</td>
    </tr>
  </tbody>
</table>
<script>
  function highlightRow(event, fn) {
    event.target.closest("tr").classList[fn]("highlight");
  }
  document.querySelectorAll(".hoverable").forEach((elm) => {
    elm.addEventListener("mouseenter", (e) => highlightRow(e, "add"));
    elm.addEventListener("mouseleave", (e) => highlightRow(e, "remove"));
  });
</script>

Open example page.

Home