jQuery triggering a click event appears to be running one step behind – Education Career Blog

I am using tablesorter plugin which is great. I have had to clone the original header and then re-insert the clone above a scrollable area.

To fire the tablesorter plugin on the hidden old table header elements i am triggering a click using .trigger() on the hidden table when a user clicks on the visible cloned table.

Here is the jQuery:

    $('.w_price_assess').delegate('#quotations_clone thead th', 'click', function() {

        var $cloneTh = $(this);
        var $cloneThIndex = $cloneTh.index('#quotations_clone thead th');

        $('#quotations thead th:eq(' + $cloneThIndex + ')').trigger('click');

        var $classList =$('#quotations thead th:eq(' + $cloneThIndex + ')').attr('class').split(/\s+/);            


        $.each($classList, function(index, item){
            if (item==='headerSortDown') {
               $('#quotations_clone thead th').removeClass('headerSortUp headerSortDown'); 
               $('#quotations_clone thead th:eq(' + $cloneThIndex + ')').addClass('headerSortDown');
            } else if (item==='headerSortUp') {
                $('#quotations_clone thead th').removeClass('headerSortUp headerSortDown');
                $('#quotations_clone thead th:eq(' + $cloneThIndex + ')').addClass('headerSortUp');
            } else {
                //$('#quotations_clone thead th').removeClass('headerSortUp headerSortDown');


The issue that is occurring is that when i first click on the cloned th element it does not immediately bring back the class that table sorter appends to the hidden th element.

I need it to register at the same time and am not sure how to go about it?


I managed to solve this by using a global variable like so:

    var $orginalHead = $("#tablesorter-demo thead");

    globalIndex = null;

    .wrap('<table id="sorter-clone" />');

    $("body").delegate("#sorter-clone thead th", "click", function() {
        var $tHeader = $(this);
        $tHeaderIndex = $tHeader.index("#sorter-clone thead th");
        $('#tablesorter-demo thead th:eq(' + $tHeaderIndex + ')').trigger('click'); 

    $("#tablesorter-demo").bind("sortEnd", function() {
        var $classList = $('#tablesorter-demo thead th:eq(' + $tHeaderIndex + ')').attr('class').split(/\s+/);
        replaceClasses($classList, $tHeaderIndex, globalIndex);                 

    function replaceClasses(classes, index, oldIndex) {

        globalIndex = index;
        var list = classes.toString().replace(",", " ");
        var oldHead = $("#sorter-clone thead th:eq(" + oldIndex + ")").removeAttr("class");
        var newHead = $("#sorter-clone thead th:eq(" + index + ")").removeAttr("class").addClass(list);         

        if (oldIndex !== null) {
            return {x:oldHead, y:newHead};
        } else {

Leave a Comment