Search code examples
jquerycell

How to highlight cell on hover with exceptions


I'm trying to highlight a table cell on hover. That's easy enough with jQuery or CSS, but I have a number of small divs within the cell and when these are hovered I want the div only to highlight and NOT the whole cell;

eg, the following cell...

So the image shows one table cell with 10 divs; when one of the small rectangle divs are hovered they need to be highlighted, but when any part of the cell excluding the divs is hover then the itself is highlighted.


Solution

  • Here's one way of doing it with jQuery:

    $(function() {
        var td = $("td");
    
        // add/remove .hovering for table cells as normal
        td.hover(function() {
            $(this).addClass("hovering");
        }, function() {
            $(this).removeClass("hovering");
        })
    
        // add/remove .hovering for <div> and do opposite for parent <td>
        $("div").hover(function() {
            $(this).addClass("hovering");
            td.removeClass("hovering");
        }, function() {
            $(this).removeClass("hovering").parents("td").addClass("hovering");
        })
    })
    div {
      background-color: #fff;
      border: 1px solid grey;
      display: inline-block;
      min-width: 50px;
      min-height: 20px;
      margin: 3px;
    }
    div.hovering {
      background-color: lightskyblue;
    }
    table {
      text-align: center;
      width: 650px;
    }
    td {
      border: 1px solid black;
      font-size: 0;
      padding: 5px;
    }
    td.hovering {
      background-color: #ddd;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
        <tbody>
            <tr>
                <td>
                    <div></div>
                    <div></div>
                    <div></div>
                    <div></div>
                    <div></div>
                    <div></div>
                    <div></div>
                    <div></div>
                    <div></div>
                    <div></div>
                </td>
                <td>
                    <div></div>
                    <div></div>
                    <div></div>
                    <div></div>
                    <div></div>
                    <div></div>
                    <div></div>
                    <div></div>
                    <div></div>
                    <div></div>
                </td>
            </tr>
        </tbody>
    </table>