Search code examples
jqueryfilterzebra-striping

Add zebra striping but ignore hidden elements


I have the following code which filters a list according to what class is added to the li element. The zebra striping works fine when all items are showing but when you filter and lets say one of the list items is hidden teh zebra stripe goes out of sync. Is there a way around this?

I have checked this post but ie did not work jQuery Table Zebra Striping with hidden rows

Thanks.

//Filter
$("#local-clubs-list li:visible:even").addClass("even");

$('ul#filter a').click(function() {  
    $(this).css('outline','none');  
    $('ul#filter .current').removeClass('current');  
    $(this).parent().addClass('current');  

    var filterVal = $(this).text().toLowerCase().replace(' ','-');  

    $('ul#local-clubs-list li').each(function() {                                 
        if(!$(this).hasClass(filterVal)) {  
            $(this).fadeOut('normal').addClass('hidden');
        } else {  
            $(this).fadeIn('slow').removeClass('hidden');
        }  

        $("#local-clubs-list li").removeClass("even");


        $("#local-clubs-list li:visible:nth-child(even)").addClass("even");
    });  


    return false;  
}); 

$('ul#filter a:eq(0)').trigger('click');

What I am seeing in firbug is

<li class="northern even">
<li class="northern">
<li class="north-dublin hidden even" style="display: none;">
<li class="northern">
<li class="northern even">
<li class="northern">
<li class="northern even">
<li class="northern">
<li class="northern even">

Solution

  • For some reason hidden doesn't work well and I had to add and remove classes. Here is the fonal code that works.

    //Filter
    
        function zebraRows(selector, className)
        {
            $(selector).removeClass(className).addClass(className);
        }
        $('#local-clubs-list li').addClass('visible');
    
        $('ul#filter a').click(function() {  
            $(this).css('outline','none');  
            $('ul#filter .current').removeClass('current');  
            $(this).parent().addClass('current');  
    
            var filterVal = $(this).text().toLowerCase().replace(' ','-');  
    
            $('ul#local-clubs-list li').each(function() {                                 
                if(!$(this).hasClass(filterVal)) {  
                    $(this).fadeOut('normal').addClass('hidden');
                    $(this).fadeOut('normal').removeClass('visible');
    
                } else {  
                    $(this).fadeIn('slow').removeClass('hidden');
                }  
            });  
    
            $('#local-clubs-list li').removeClass('even');
            zebraRows('#local-clubs-list .visible:even', 'even');
            $('#local-clubs-list li').addClass('visible');
            return false;  
        }); 
    
        $('ul#filter a:eq(0)').trigger('click');