Implement table styling after concealing rows (Twitter Bootstrap)

Hey there, I am currently working with Bootstrap and have a table that is striped. Users can filter this table by selecting different options on a form. The Javascript code I've written interprets the form input and hides rows in the table that don't meet the selected criteria.

My issue is that this filtering process disrupts the striping of the table row colors, causing adjacent gray rows to be next to one another and same for white rows.

I want to find a solution that will reapply the table striping based on the visible rows after the filtering has been done. Can anyone suggest how I might achieve this?

My aim is to avoid using .remove() on the table rows because I may need to show them again if the user changes the filter criteria. Additionally, I'm looking to steer clear of using AJAX to dynamically update the table based on filter inputs, preferring instead to stick with hiding DOM elements.

Your assistance would be greatly appreciated! Please let me know if you require further clarification :)

Answer №1

It appears that Bootstrap 4 has a unique approach to implementation. Referencing @Anthony's response, the following demonstrates how it functions:

$("tr:visible").each(function (index) {
    $(this).css("background-color", !!(index & 1)? "rgba(0,0,0,.05)" : "rgba(0,0,0,0)");
});

Instead of applying the "stripe" class name, tables are now striped using purely CSS.

Answer №2

A common frustration with table striping is having to constantly reapply it after updates. The most efficient solution may be to utilize jQuery to reapply the striping each time:

$("tr:not(.hidden)").each(function (index) {
    $(this).toggleClass("stripe", !!(index & 1));
});

Answer №3

Anthony's solution didn't quite meet my needs. I found that it didn't successfully hide the Bootstrap table class table-striped, and there wasn't a readily available built-in class like stripe for formatting table rows.

Here's what I came up with to handle filtering rows in a table identified by the id "reports":

If you want to avoid defining a CSS class called "stripe" for <tr> elements, you can try this alternative:

// Remove striped styling from table as Bootstrap striping won't work for filtered rows
$("table#reports").removeClass("table-striped");

// Apply alternate row striping
$rows.each(function (index) {
  // Reset any previous color changes
  $(this).css("background-color", "inherit");
  if ( index % 2 == 0) {
    $(this).css("background-color", "#f9f9f9");
  }
});

This method provides a quick and easy way to achieve row striping without creating a separate CSS class.

Answer №4

This answer mirrors the response from @Jacobski found here, while retaining the hover effect of a bootstrap table-hover.

$("tr:visible").each(function (index) {
    $(this).css("background-color", !!(index & 1) ? "rgba(0,0,0,.05)": "rgba(0,0,0,0)");
    if (!(index & 1)) {
        $(this).hover(
            function () {  //On hover over
                $(this).css("background-color", "rgba(0,0,0,.07)");
            },
            function () {  //On hover out
                $(this).css("background-color", "rgba(0,0,0,0)");
            }
        )
    }
});

Answer №5

Taking inspiration from the suggestions of @Jacob and @yehuda, my approach enhances bootstrap4 tables with both ".table-striped" and ".table-hover" functionalities. To optimize performance, I utilized CSS for the hover effect instead of relying solely on JavaScript (as observed in a slight delay when testing @yehuda's snippet).

    // Custom CSS
    <style>
    .table-striped tbody tr.visible-odd {
      background-color: rgba(0, 0, 0, 0.05);
    }

    .table-striped tbody tr.visible-even {
      background-color: rgba(0, 0, 0, 0.00);
    }

    .table-hover tbody tr.visible-even:hover {
      background-color: rgba(0, 0, 0, 0.075);
    }
    </style>

    // Custom JS
    $("tr:visible").each( function(index, obj) {
        if (index % 2) {
            $(this).addClass('visible-odd').removeClass('visible-even');
        } else {
            $(this).addClass('visible-even').removeClass('visible-odd');
        }
    });

Answer №6

In my experience, I have found that reapplying striping on tables with hidden rows works well using the following code:

$("table#ProductTable").removeClass("table-striped");
$("table#ProductTable").addClass("table-striped");

Answer №7

@Jacobski provided an excellent solution to my issue. However, I encountered a problem with multiple tables on my pages where the background of header rows would change separately. Additionally, the table rows that were always visible had the class "accordion-toggle," which I targeted in Bootstrap 5 fashion! (I'm not well-versed in JavaScript, so there might be a more efficient way to achieve what I did)

$("tr:visible").each(function (index) {
    if ($(this).hasClass("tb-header")) {
        rowIndex = 0; // Resets the rowIndex for new table iteration
    } else {
        if ($(this).hasClass("accordion-toggle")) {
            $(this).css("background-color", !!(rowIndex & 1)?  "rgba(0,0,0,0)" : "rgba(0,0,0,.05)");
            rowIndex++;
        }
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting elements relative to a div can be achieved by using CSS positioning properties

I'm currently learning HTML/CSS and facing a challenge in setting elements relative to a container. After reading about the differences between "relative" and "absolute" positioning, I understand that "relative" positions an element relative to where ...

Is it possible to identify users using an iPhone while they are utilizing "Private Browsing" mode?

Looking for a solution to detect private browsing mode in my jquerymobile App. I need localStorage and sessionstorage to work properly, but prompting users to enable cookies when private browsing is enabled doesn't solve the issue. Is there a way to t ...

Fetch begins its journey to retrieve html content before reaching its intended destination

While using fetch to populate a webpage with HTML, the backend server is self-hosted, the DNS is managed with Cloudflare, and Nginx is being used. The application is running on Node.js, Express, and EJS. However, an issue arose where the fetch operation st ...

Retrieve JSON data by making an AJAX request to a PHP file using the POST method

I am looking to extract data from a form using an AJAX call. The information is received in PHP as a string that looks like: 'fname':'abc','lname':'xyz','email':'','pass':'',& ...

Resolving peer dependency conflict during npm installation

When attempting to run npm install @react-navigation/native @react-navigation/native-stack, I encountered the following errors: npm WARN ERESOLVE overriding peer dependency npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While ...

jQuery: Issue with progress indicator not displaying or hiding correctly during AJAX requests

In an HTML page, I have different sections created using DIV tags and updated using AJAX calls. One of these divs serves as a progress indicator to inform the user about ongoing background processes. However, I'm facing an issue where the progress in ...

What is the best way to ensure a stable background image using CSS?

I have successfully created my navigation section and now I am working on the main body of the website. However, when I try to add a background image, it ends up appearing on the navbar as well. Can someone please assist me with this issue? Below is the HT ...

My email submission function is malfunctioning

my contact form in my website is not working properly. I have tried troubleshooting the issue by checking the contact.php file but it doesn't seem to be the problem. The script that I am using for the form submission is shown below: <!--Contact U ...

Why is it necessary to use "new" with a Mongoose model in TypeScript?

I'm a bit confused here, but let me try to explain. When creating a new mongoose.model, I do it like this: let MyModel = moongoose.model<IMyModel>("myModel", MyModelSchema); What exactly is the difference between MyModel and let newModel = ne ...

Tips for changing font styles using Polymer

I'm new to working with Polymer.js and CSS. My goal is to have text in todo.item display normally when todo.done is false, and with a line-through style when todo.done is true. I'm considering using CSS for this task, but I'm unsure how to ...

NodeJS's pending ajax post using SailsJS

I'm experiencing an issue with processing AJAX data in my sailsJS app. The ajax post data always stays in the pending state, here is the code from my view: <script type="text/javascript"> $('#submit').click(function(){ $.ajax ...

Is there a bug causing the Admin LTE content height issue? Looking for solutions to fix it

What's the reason behind the oversized footer? The footer appears normal when I resize or zoom the page, why is that? How can this be resolved? ...

Stopping background content from scrolling while using position: fixed

Is there a way to prevent content from scrolling behind a fixed position element? Check out the demo here .navbar-default { background-color: #4c68f9; margin-bottom: 0; border: none; } .navbar-default.affix { background-color: #4762ed; margin ...

Is it possible to read the content from both the parent $(this) selector and its individual children

Is there a way to extract contents from the given selector, $(this), and its child elements separately? <div class="para"> <h1 class="hd">heading 1</h1> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc tincid ...

What is the best way to maintain an ongoing sum of multiple values using bacon.js?

Experimenting with the power of bacon.js. I want to maintain a dynamic total of values from a set of text inputs. The example on the github page utilizes the .scan method along with an adding function, which functions well for simple increment and decremen ...

Controlling Fabric in Three.JS

(I'm still learning so forgive me if this is a beginner question.) I'm currently working on fitting a cloth material to a character model in Three.JS. What would be the most effective approach for this? Should I create a complete garment as cloth ...

Revisiting Angular: The Curious Case of an Object Attribute Altering Attributes on Two Separate Objects

Creating a website with Angularjs involves working with an array of objects: $scope.fieldsToShow = [ { "fields": {}, "type": "LOGGED_IN" }, { "fields": {}, "type": "PERSONAL", "user": 2, "name": ...

Leveraging the power of HTML5's details element for optimized printing

The <details> HTML5 element is used to provide a simple show/hide functionality. While this feature works well on-screen, it poses an issue when printing as any closed <details> elements disappear in the printed version. I attempted to fix th ...

Having difficulty changing the $theme-color variable in bootstrap

Utilizing Bootstrap 4.0 along with SASS Within my style.scss file, you will find the following code: @import "../bootstrap/scss/bootstrap"; @import "colors"; @import "main"; Meanwhile, the _colors.scss file contains the following code: $bg-white : whi ...

Steps to update the package version in package.json file

If I remove a package from my project using the following command: npm uninstall react The entry for this package in the package.json file does not disappear. Then, when I install a different version of this package like so: npm install <a href="/cdn ...