how to handle slow jQuery addClass effect?

Tags: ,



I am doing a pagination list of page numbers for users to select the page. When a user clicks any page it will run the ajax request first and then load the data to render the page. Then the jQuery.addClass is run to show which page number is currently active, by adding the ‘active’ class – addClass('active').

The problem is the jQuery.addClass effect works sometimes but not everytime (addClass just doesn’t add the class to the selected element). I think this is because the DOM is loaded too fast and jQuery can’t catch up. Even when I use setTimeout it still doesn’t work sometimes. How can I handle it?

$(() => {

    //Moving page number and
    //Set Active for moving page number
    $(document).on("click", "a.btn-pagination", function(event){
        $('#page_loading').css('display', ''); //--> display the page loading gif
        var num = $(this).attr('data-page');

        $('#result_container').load(base_url+'store/movePage/'
        + $(this).attr('data-page'));

        setTimeout( () => {
            updateButton();
            $('.btn-pagination[data-page = ' + num + ']').show().addClass('active');
        }, 300);

        setTimeout( () => {
            $('#page_loading').css('display', 'none'); //--> hide the page loading gif
        }, 400);
    });

});

function updateButton(){
    let dateValue = $('#currentdate').text().trim();


    if(dateValue >= maxdt){
        $('#next_btn').html('<a class="btn-disable" style="color: gray;">Newer <i class="ace-icon fa fa-arrow-right"></i></a>');
    }
    else {
        $('#next_btn').html('<a href="#" onclick="nextDate()">Newer <i class="ace-icon fa fa-arrow-right"></i></a>');
    }

    if(dateValue <= mindt){
        $('#previous_btn').html('<a class="btn-disable" style="color: gray;"><i class="ace-icon fa fa-arrow-left"></i> Older</a>');
    }
    else {
        $('#previous_btn').html('<a href="#" onclick="prevDate()"><i class="ace-icon fa fa-arrow-left"></i> Older</a>');
    }
}

Answer

It is better to use callbacks when using async operations, as they provide certainty that the callback won’t run until the async operation has finished.

Instead of this,

$('#result_container').load(base_url+'store/movePage/'
        + $(this).attr('data-page'));

use a callback as part of your load

$('#result_container').load(base_url+'store/movePage/'
        + $(this).attr('data-page'), function(){
  updateButton();
  $('.btn-pagination[data-page = ' + num + ']').show().addClass('active');
});

Then remove this:

            updateButton();
            $('.btn-pagination[data-page = ' + num + ']').show().addClass('active');
        }, 300);


Source: stackoverflow