Search code examples
twitter-bootstrapbootstrap-4bootstrap-5

dynamically change the colour of a table-hover in bootstrap based on a cell value


I have a simple table using table-hover

Fiddle

<table class="table table-hover">
  <thead>
    <tr>
      <th scope="col">Fleet</th>
      <th scope="col">Location</th>
      <th scope="col">Status</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">R132</th>
      <td>High St</td>
      <td>ON TIME</td>
    </tr>
    <tr>
      <th scope="row">R100</th>
      <td>St Martins</td>
      <td>LATE</td>
    </tr>
    <tr>
      <th scope="row">W101</th>
      <td>Cafe St</td>
      <td>EARLY</td>
    </tr>
  </tbody>
</table>

I've found ways to change the default hover colour, and I can change the table row or cell background with the usual conditional formatting but that's not what I'm looking for.

e.g

.table-hover tbody tr:hover td, .table-hover tbody tr:hover th {
  background-color: #color;
}

I'm trying to format the hover colour based on the value in the 'status' column with red for 'late' and green for 'early' etc. so that I can maintain the same look and feel of the table.


Solution

  • You can simply add class to your tr indicating the color you want to see on hover

    .ontime:hover {
      background-color: yellow;
    }
    
    .late:hover {
      background-color: red;
    }
    
    .early:hover {
      background-color: green;
    }
    <table class="table table-hover">
      <thead>
        <tr>
          <th scope="col">Fleet</th>
          <th scope="col">Location</th>
          <th scope="col">Status</th>
        </tr>
      </thead>
      <tbody>
        <tr class="ontime">
          <th scope="row">R132</th>
          <td>High St</td>
          <td>ON TIME</td>
        </tr>
        <tr class="late">
          <th scope="row">R100</th>
          <td>St Martins</td>
          <td>LATE</td>
        </tr>
        <tr class="early">
          <th scope="row">W101</th>
          <td>Cafe St</td>
          <td>EARLY</td>
        </tr>
      </tbody>
    </table>