Warm tip: This article is reproduced from stackoverflow.com, please click
bootstrap-4 javascript jquery

Jquery hiding table rows hide() vs fadeOut() stripe table

发布于 2020-03-27 10:25:00

I am trying to reapply table striping from Bootstrap after hiding table rows with Jquery. A checkbox is used to hide rows in which a cell contains "No". When I use the hide() function, the striping gets applied correctly after hiding rows, but if I use the fadeOut() function, the striping does not get applied correctly

$(document).ready(function () {
    $('#customSwitch1').change(function () {
        if (!this.checked) 
            $('#indexTable tr td:contains(No)').parent().fadeIn('fast');
        else 
            $('#indexTable tr td:contains(No)').parent().hide();

        $("#indexTable tr:visible").each(function (index) {
            $(this).css("background-color", !!(index & 1)? "rgba(0,0,0,0)" : "rgba(0,0,0,0.05)");
    });
    });
    $('#customSwitch1').change();

});

If I replace hide() with fadeout, the striping does not get applied correctly (or put a duration into the hide function)

Questioner
ys1122
Viewed
77
Lapskaus 2019-07-03 23:10

You need to use a callback function in your fade function so that the rows are actually invsisible / visible when you run your code to reapply the striping. Otherwise the animation of the fade function is not done, the row is still visible and your striping is messed up

$(document).ready(function () {
    $('#customSwitch1').change(function () {
        if (!this.checked) {
            $('#indexTable tr td:contains(No)').parent().fadeIn('slow', reapplyStripes);
        }else {
            $('#indexTable tr td:contains(No)').parent().fadeOut('slow', reapplyStripes);
        }
    });
    $('#customSwitch1').change();

});

function reapplyStripes() {
$("#indexTable tr:visible").each(function (index) {
            $(this).css("background-color", !!(index & 1)? "rgba(0,0,0,0)" : "rgba(0,0,0,0.05)");
    });
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<input type="checkbox" id="customSwitch1" />
<table class="table table-striped" id="indexTable">
<tr>
<td>YES</td>
</tr>
<tr>
<td>No</td>
</tr>
<tr>
<td>Yes</td>
</tr>
<tr>
<td>Yes</td>
</tr>
</table>