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.

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

Open example page.