skip to Main Content

The problem I am facing is similar to this post: HTML table how highlight row on hover except first column?. However the replies here are not the effect that I am looking for. I am looking for both the first 2 columns to light up when I hover over either one, and for the 3rd column to not light up anything at all when I hover over it.

2

Answers


  1. If you need mouse events in the 3rd column this cannot be done without JS.

    The problem that the 3rd column should be disabled. It could be done with pointer-events:none. But if we need mouse events in the 3rd columns here’s solution:

    You could use the nth-child CSS pseudo class and some Javascript:

    https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

    'mousemove mouseleave'.split(' ').forEach(name =>
      $table.addEventListener(name, syncHover)
    );
    
    function syncHover(e) {
    
      $table.querySelector('tr.hover')?.classList.remove('hover');
    
      const $td = e.target.closest('td');
    
      $td && [...$td.parentElement.children].indexOf($td) < 2 &&
        $td.parentElement.classList.add('hover');
    
    }
    table tr.hover>td:nth-child(-n + 2) {
      background: lightgray;
      cursor: pointer;
    }
    
    table td {
      padding: 5px 10px;
    }
    
    table {
      border-collapse: collapse;
      background: #eee;
    }
    <table id="$table">
      <tr>
        <td>col1</td>
        <td>col2</td>
        <td>col3</td>
      </tr>
      <tr>
        <td>col1</td>
        <td>col2</td>
        <td>col3</td>
      </tr>
      <tr>
        <td>col1</td>
        <td>col2</td>
        <td>col3</td>
      </tr>
      <tr>
        <td>col1</td>
        <td>col2</td>
        <td>col3</td>
      </tr>
    </table>
    Login or Signup to reply.
  2. Please don’t use any nor for this, two rule’s are enough.

    Select all the tr:hover, and then exclude the last col by using td:not(:last-of-type).

    Then disable all pointer-events on the last column to disable that triggering the hover.

    table > tbody > tr:hover td:not(:last-of-type) {
        background-color: red;
    }
    
    table > tbody > tr > td:last-of-type {
        pointer-events: none;
    }
    <table border cellpadding="5">
        <tbody>
            <tr><td>F</td><td>o</td><td>o</td><td>B</td><td>a</td><td>r</td></tr>
            <tr><td>F</td><td>o</td><td>o</td><td>B</td><td>a</td><td>r</td></tr>
        </tbody>
    </table>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search