Why does my hover highlights over row and column in table get stuck on load sometimes

Viewed 7

I've been getting some great help here on row and column highlighting on my html table when I hover with mouse. However, sometimes when the page first loads the hightlighter will get stuck (see image below). One gets stuck and other moves ok, but theres 2 highlighters (not expected). If I don't move my mouse for a few seconds after the page load it doesn't get stuck and works fine. What do you think is happening here?

The proof of concept code works great, but in production page has to goto database and there's of course a delay and in production is where it's happening.

https://stackoverflow.com/a/73788969/139698

<html>
<head>
    <title></title>
    <style>
        table {
            border-spacing: 0px;
        }

        td {
            border: 1px solid #bbb;
            padding: 0.2em;
        }

        /*            tr:first-child, td:first-child {
                background: lightgrey;
            }*/

        .hovered-per {
            background-color: green;
            color: white;
        }

        .hovered {
            background: yellow;
        }

        .hovered-cell {
            background: orange;
        }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery-3.6.0.min.js" type="text/javascript"></script>
</head>
<body>
    <table border="1">
        <tr>
            <td>row1 col1</td>
            <td>row1 col2</td>
            <td>row1 col3</td>
            <td>row1 col4</td>
        </tr>
        <tr>
            <td>row2 col1</td>
            <td>row2 col2</td>
            <td>row2 col3</td>
            <td>row2 col4</td>
        </tr>
        <tr>
            <td>row3 col1</td>
            <td>row3 col2</td>
            <td>row3 col3</td>
            <td>row3 col4</td>
        </tr>
        <tr>
            <td>row4 col1</td>
            <td>row4 col2</td>
            <td>row4 col3</td>
            <td>row4 col4</td>
        </tr>
    </table>
    <script>
        $(function () {
            const removePersistant = () => {
                $('.hovered-per').removeClass("hovered-per");
                $('.hovered-cell').removeClass("hovered-cell");
            };

            $('td').hover(function () {
                $(this).toggleClass('hovered-cell')
                $(this).parent('tr').toggleClass('hovered');
                $('td:eq(' + this.cellIndex + ')', 'tr').toggleClass('hovered');
                $('.hovered-per').removeClass("highlight");
            });

            $('td').click(function () {
                removePersistant();
                //$(this).addClass('hovered-cell')
                $(this).parent('tr').toggleClass('hovered-per');
                $('td:eq(' + this.cellIndex + ')', 'tr').toggleClass('hovered-per');
            });
        });
    </script>
</body>
</html>

enter image description here

0 Answers
Related