Column Hacks

by Tonio Loewald

HTML

<button id="showall">Show All</button>
<button id="hide34">Hide Columns 3 and 4</button>
<table>
    <thead>
         <tr>
             <th>A</th>
             <th>B</th>
             <th>C</th>
             <th>D</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>100</td>
            <td>200</td>
            <td>300</td>
            <td>400</td>
        </tr>
        <tr>
            <td>100</td>
            <td>200</td>
            <td>300</td>
            <td>400</td>
        </tr>
    </tbody>
</table>

CSS

.col-over {
    background-color: yellow;
}

JavaScript

$('#showall').on('click', function(){
        $('th,td').show();
    });

    $('#hide34').on('click', function(){
        $('th:nth-child(n+3),td:nth-child(n+3)').hide();
    });

    $('th,td')
        .on('mouseenter', function(){
            var n = $(this).prevAll().length + 1;
            $('tr :nth-child(' + n + ')').addClass('col-over');
        })
        .on('mouseleave', function(){
            var n = $(this).prevAll().length + 1;
            $('tr :nth-child(' + n + ')').removeClass('col-over');
        })
        .on('mouseup', function(){
            var n = $(this).prevAll().length + 1;
            $('tr :nth-child(' + n + ')').hide();
        });