Search code examples
javascriptjqueryhtmlajaxmcustomscrollbar

Losing mCustomScrollbar effect when performing an ajax call


I'm using mCustomScrollbar to replace the default scrollbars in a div tag containing a table that I draw using javascript to help me reload it when performing ajax calls, here is my HTML code :

<!-- the div that will contain the table-->
<div id="countriesTable" class="customScroll" data-mcs-theme="dark">
</div>

Here is the code of the function that loads the data in the table and draws it inside the div

function reloadTable(data, id) {
        var str = '<table class="table"><thead>' +                    
                '<tr><th> Column1 </th>' +
                '<th> Column2 </th>' +
                '<th> Column3 </th>' +
                '<th> Column4 </th></tr></thead><tbody>';
        for (var property in data) {
            if (data.hasOwnProperty(property)) {                    
                str += '<tr>'
                str += '<td>' + data[property][0] + '</td>' +
                '<td>' + data[property][1] + '</td>' +
                '<td>' + data[property][2] + '</td>' +
                '<td>' + data[property][3] + '</td></tr>';
            }
        }
        str += '</tbody></table>';
        $(id).html(str);
    }

And of course the call of the function to load data and also the function that applies the custom scroll bar effect :

reloadTable(myData, '#countriesTable');
$(".customScroll").mCustomScrollbar();

When the page is loaded the div gets the custom scrollbar successfully, but when I perfom an ajax call to reload data into my table, and I draw it another time using reloadTable function I lose the scrollbar effect. I've tried to recall the mCustomScrollbar inside the ajax success function but in vain.


Solution

  • I think you need to remove current mCustomScrollbar like this:

    $('.customScroll').mCustomScrollbar("destroy")
    $('#countriesTable').html("")
    reloadTable(myData, '#countriesTable');
    $(".customScroll").mCustomScrollbar();