Update alternating list row color after removal using jQuery

1.7k views Asked by At

I am using jQuery to alternate the background colors and add radii to some unordered list items like so:

// Alternate row colors for group listing and add top/bottom radii
$('li.groupList:even').css({backgroundColor: '#e4e4e4'});
$('li.groupList:odd').css({backgroundColor: '#ededed'});
$('li.groupList:first').addClass('rtm');
$('li.groupList:last').addClass('rbm');

However, if I remove one of the list items using the actual remove() method, the colors and radii do not update.

// Remove group members
$("[id^='removeGroupMember_']").click(function () {
    $(this).parent().slideUp("fast", function () {
        $(this).remove();
    });
});

Is this because the browser does not get notified of the list array change or is this something I should just be doing using CSS only (i.e. using li.groupList:nth-child(even) etc.)?

The reason I was using jQuery to begin with was because I assumed it was cross-browser compliant moreso than CSS3 selectors (but please enlighten me if you think otherwise!).

1

There are 1 answers

1
Šime Vidas On BEST ANSWER

Call this function whenever you remove one of the list items:

function update() {
    var l = $('li.groupList').removeClass('rtm rbm').removeAttr('backgroundColor');

    l.filter(':even').css({backgroundColor: '#e4e4e4'});
    l.filter(':odd').css({backgroundColor: '#ededed'});
    l.first().addClass('rtm');
    l.last().addClass('rbm');
}