Search code examples
javascriptjquerysortingtablesorter

JQuery Tablesorter: Have column show as another is sorted


I am creating a sorted table, I would like it when I click for one column to be sorted another column shows next to it. I currently have it that as you click it once it shows, the problem with this is when it is sorted the other way the column disappears when I still need to see it. When another column is clicked I would also want the other one to hide and the one clicked to show. Please let me know if i haven't explained this well!! This code is shown below from jquery:

$(document).ready(function(){
   $("#CATAID").click(function(){
        $("td:nth-child(7),th:nth-child(7)").toggle();
    });
});

Does anyone have any idea how this can be done?


Solution

  • A more efficient method of doing this would be with css... then large tables won't be effected by lag while hiding/showing the table cells (demo):

    CSS

    th:nth-child(4), td:nth-child(4) {
        display: none;
    }
    .toggle th:nth-child(4),
    .toggle td:nth-child(4) {
        display: table-cell;
    }
    

    HTML

    <table class="tablesorter-blue">
        <thead>
            <tr>
                <th>AlphaNumeric</th>
                <th>Numeric</th>
                <th class="toggler">Animals</th>
                <th class="toggler">Sites</th>
            </tr>
        </thead>
        <tbody>
        ...
        </tbody>
    </table>
    

    Javascript

    $(function () {
        $('th').click(function(){
            // toggle "toggle" class name on the table when the
            // header with a class name of "toggler" is clicked
            $('table').toggleClass( 'toggle', $(this).hasClass('toggler') );
        });
    
        $('table').tablesorter();
    });
    

    The reason the last column has a "toggler" class is to allow it to be sorted.

    A method to allow css animation could be added, but I think it would only work if the toggled column had the contents wrapped in a div that was animated (in width) instead of trying to animate the table cells.