Utilize Bootstrap's table-hover feature in combination with rowspan to effectively highlight every row associated with a specific

I am attempting to replicate the functionality of the table-hover class on a Bootstrap table that contains multiple cells with different rowspan values. This means I want to highlight every cell within the same row. Below is an example demonstrating the current behavior of the table-hover class:

.td-centered {
  vertical-align: middle!important;
  text-align: center;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<table class="table text-center text-nowrap table-bordered table-hover">
  <thead>
    <tr>
      <th scope="col" class="h5 font-weight-bold">
        Date
      </th>
      [......]   

The desired behavior is depicted below:

.td-centered {
  text-align: center;
  vertical-align: middle !important;
}

.red-bg {
  background-color: red;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />
<table class="table text-center text-nowrap table-bordered">
  <thead>
    <tr>
      <th scope="col" class="h5 font-weight-bold">
        Date
      </th>
     [...]
  </tbody>
</table>

To achieve this, jQuery may be necessary. While utilizing only Bootstrap for the solution is preferable, standard CSS can also be used. Any assistance or insight you can provide would be greatly appreciated :)

Answer №1

This is the solution I devised:

jQuery(() => {
  if ($("#table-multi-hover").length) {
    const headerValues = Array.from($("thead")[0].children[0].children)
      .map(item => item.innerText.toLowerCase());

    let table = [];

    const tableCells = Array.from($("tbody")[0].children)
      .map(item => item.children)
      .map(item => Array.from(item));

    for (let i = 0; i < tableCells.length; i++) {
      let tempObj = {};
      for (let j = 0; j < tableCells[i].length; j++) {
        tempObj[tableCells[i][j].attributes.rep.value] = tableCells[i][j];
      }

      for (let j = 0; j < headerValues.length; j++) {
        if (i != 0 && tempObj[headerValues[j]] == undefined) {
          tempObj[headerValues[j]] = table[i - 1][headerValues[j]];
        }
      }
      table.push(Object.assign({}, tempObj));
    }

    $("tbody td, tbody th").on("mouseover", event => {
      const rowIndex = parseInt(event.currentTarget.parentElement.attributes.i.value);
      const rep = event.currentTarget.attributes.rep.value;
      const rowspan = event.currentTarget.attributes.rowspan != undefined ?
        parseInt(event.currentTarget.attributes.rowspan.value) : 1;

      for (let i = 0; i < rowspan; i++) {
        for (let j in table[rowIndex + i]) {
          $(table[rowIndex + i][j]).addClass("red-bg");
        }
      }
    });

    $("tbody td, tbody th").on('mouseleave', event => {
      const rowIndex = parseInt(event.currentTarget.parentElement.attributes.i.value);
      const rep = event.currentTarget.attributes.rep.value;
      const rowspan = event.currentTarget.attributes.rowspan != undefined ?
        parseInt(event.currentTarget.attributes.rowspan.value) : 1;

      for (let i = 0; i < rowspan; i++) {
        for (let j in table[rowIndex + i]) {
          $(table[rowIndex + i][j]).removeClass("red-bg");
        }
      }
    });
  }
});
td,
th {
  text-align: center;
  vertical-align: middle !important;
}

.red-bg {
  background-color: red;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table text-center text-nowrap table-bordered" id="table-multi-hover">
  <thead>
    <tr>
      <th scope="col" class="h5 font-weight-bold">
        Date
      </th>
      <th scope="col" class="h5 font-weight-bold">
        Title
      </th>
      <th scope="col" class="h5 font-weight-bold">
        Amount
      </th>
      <th scope="col" class="h5 font-weight-bold">
        Price
      </th>
      <th scope="col" class="h5 font-weight-bold">
        Value
      </th>
    </tr>
  </thead>

  <tbody>
    <tr i="0">
      <th rowspan="3" scope="row" rep="date">2020-06-25</th>
      <td rowspan="2" rep="title">Some name 1</td>
      <td rep="amount">2</td>
      <td rep="price">30.00 PLN</td>
      <td rep="value">60.00 PLN</td>
    </tr>
    <tr i="1">
      <td rep="amount">1</td>
      <td rowspan="2" rep="price">20.00 PLN</td>
      <td rep="value">20.00 PLN</td>
    </tr>
    <tr i="2">
      <td rep="title">Some name 2</td>
      <td rep="amount">2</td>
      <td rep="value">40.00 PLN</td>
    </tr>
    <tr i="3">
      <th rowspan="3" scope="row" rep="date">2020-06-24</th>
      <td rowspan="2" rep="title">Some name 1</td>
      <td rep="amount">2</td>
      <td rep="price">30.00 PLN</td>
      <td rep="value">60.00 PLN</td>
    </tr>
    <tr i="4">
      <td rep="amount">1</td>
      <td rowspan="2" rep="price">20.00 PLN</td>
      <td rep="value">20.00 PLN</td>
    </tr>
    <tr i="5">
      <td rep="title">Some name 2</td>
      <td rep="amount">2</td>
      <td rep="value">40.00 PLN</td>
    </tr>
  </tbody>
</table>

The required steps to implement this solution are:

  1. Assign the id attribute to your table and set it as table-multi-hover.
  2. Include the i attribute in your tr within tbody, starting at index 0.
  3. Add the rep attribute to your td and th with values corresponding to the values in the table header in lowercase.

Note that this solution assumes a continuous table without gaps and no colspan attributes set. Additionally, it relies on the existence of a thead like shown in the code snippet. The added class to elements is named red-bg.

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

Is it possible to access a file on the client's PC without transferring the file to the server?

Is there a way to read an excel file directly from a user's PC in a web app and insert the cell values into a MySQL database cell by cell? Or should the file be uploaded to the server first before being read? (The web app is built using JSP) ...

Guide to adjusting icon placement on top of an image using Bootstrap 4

Is there a way to overlay an icon on top of an image? .item { position: relative; } .des { color: #fff; text-align: left; } <div class="card"> <div class="item"> <img class="card-img-top" src="images/g33.jpg" alt="Avata ...

How can you trigger a 'hashchange' event regardless of whether the hash is the same or different?

Having a challenge with my event listener setup: window.addEventListener('hashchange', () => setTimeout(() => this.handleHashChange(), 0)); Within the handleHashChange function, I implemented logic for scrolling to an on-page element whil ...

Efficiently Structuring Your Email Lists in PHP

Seeking help to solve a simple problem - I have an HTML form with arrays for multiple product entries. Snippet of the form While everything works great and I receive an email with values, the information in the email looks like this: Form data Email rec ...

Implementing automatic activation of a tab upon page load using Angular

I am currently working with a set of Bootstrap nav pills in my navigation bar. The 'ng-init' code in my Angular script sets the 'dateState' to 'past' on page load. However, I have noticed that the 'Past Events' nav p ...

Issue: The system does not recognize 'cleancss' as an internal or external command

After successfully installing clean-css via npm command line, I was eager to start using it to concatenate and minify some css files. However, my excitement quickly turned to frustration when I encountered this error: 'cleancss' is not recognize ...

Is it possible to upload a file to my web application without having configured any backend system?

Currently, I am in the process of developing a landing page that includes a form where users can input their data and send an email. I have successfully implemented the form using HTML, CSS, and JavaScript, and I have even managed to incorporate the email- ...

Tracking the progress bar as files are being uploaded via AJAX using HTML5

Currently, I have a progress bar that increments based on the number of files and their sizes. I am looking to implement an overall progress bar to display while uploading files to the server using AJAX and HTML5. Each file is uploaded individually to th ...

Embedding JavaScript within an HTML document

Need help with linking HTML files and utilizing JavaScript outputs? I have an .html file displaying a webpage with tabs that I want to link to another .html file. How can I create a link on my page to navigate to the other file? Additionally, in the linked ...

Tips for adding a class to an SVG when clicked

I want to make an SVG change color to white when clicked and its container (icon_container) to change to blue. How can I achieve this? Below is the code snippet: state = { active: false, }; click = () => { this.setState({active: !this.state.active ...

Unable to choose multiple sentences within an HTML Page displayed in a UIWebView

I am dealing with an HTML page structured as follows: <html> <body> <div id='0> <span id='0'>Hi </span> <span id='1'>How </span> <span id='2'>Are </span> <sp ...

Trigger the onChange event for a number input using JQuery

Regarding the input that has type number: <input type="number" id="input-number" onChange="DoSomething();"/> Is there a way to trigger the onChange event using jQuery? [UPDATE] I was able to achieve this with the following code: $("#input_0").tr ...

Using Python with Selenium, automate the process of clicking on each list item within

Hey there! I recently implemented the code below, and it worked perfectly. However, I'm now trying to figure out how to make it click on all the li items within a ul that have an empty class attribute. Any ideas on how to do this using Xpath? Xpath: ...

Adjust the color of text in an input field as you type (css)

I am trying to customize the appearance of my search box by making the text color white. However, even after changing the placeholder color and text color to white in my CSS code, the text color only changes to white when the user clicks out of the form. W ...

Flask does not display images in CSS files

Starting with the frontend (HTML, CSS) of my project, I then proceeded to create a Flask file with the following code: from flask import Flask, render_template app = Flask(__name__) @app.route("/", methods=["GET"]) def index(): return render_templa ...

Particle JS - Taking over the entire screen

I have incorporated Particle JS into the banner using the link provided. It should be confined within the banner, with a white background underneath displaying the header text "hello there." However, the Particle.JS effect is currently taking over the enti ...

Having trouble styling my Aside element correctly

I'm having trouble aligning my aside element on the page. It's not lining up properly with the rest of the content and is overlapping into the header area. How can I resolve this issue? Here's a snapshot of what it currently looks like: ht ...

`Error with Bootstrap breakpoints in mobile display`

While working on a responsive login layout using Bootstrap 5, I encountered a strange issue. The design looked fine in the web view, but when switching to mobile view, the md and sm breakpoints didn't trigger as expected. However, after pasting the co ...

What is the best technique for creating a preloader that can seamlessly fill the background of a vector image?

I am looking for guidance on creating a CSS3 preloader using a vector image. My goal is to have the logo start off transparent with only the border visible, and as the loading occurs, fill in from bottom to top with the background color. Thank you to ever ...

Attempting to conceal image previews while incorporating pagination in Jquery

I'm working on implementing pagination at the bottom of a gallery page, allowing users to navigate between groups of thumbnail images. On this page, users can click on thumbnails on the left to view corresponding slideshows on the right. HTML <di ...