Import the information into a td tag's data-label property

I have implemented a responsive table design that collapses for smaller screens and displays the table header before each cell.

body {
  font-family: "Open Sans", sans-serif;
  line-height: 1.25;
}
table {
  border: 1px solid #ccc;
  border-collapse: collapse;
  margin: 0;
  padding: 0;
  width: 100%;
  table-layout: fixed;
}
table caption {
  font-size: 1.5em;
  margin: .5em 0 .75em;
}
table tr {
  background: #f8f8f8;
  border: 1px solid #ddd;
  padding: .35em;
}
table th,
table td {
  padding: .625em;
  text-align: center;
}
table th {
  font-size: .85em;
  letter-spacing: .1em;
  text-transform: uppercase;
}
@media screen and (max-width: 600px) {
  table {
    border: 0;
  }
  table caption {
    font-size: 1.3em;
  }
  table thead {
    border: none;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
    color: red;
    background-color:#000;
  }
  table tr {
    border-bottom: 3px solid #ddd;
    display: block;
    margin-bottom: .625em;
  }
  table td {
    border-bottom: 1px solid #ddd;
    display: block;
    font-size: .8em;
    text-align: right;
  }
  table td:before {
    /*
    * aria-label has no advantage, it won't be read inside a table
    content: attr(aria-label);
    */
    content: attr(data-label);
    float: left;
    font-weight: bold;
    text-transform: uppercase;
  }
  table td:last-child {
    border-bottom: 0;
  }
  table td:first-child{
    color:white;
    background: #000;
  }
}
<table>
  <caption>Statement Summary</caption>
  <thead>
    <tr>
      <th scope="col">Account</th>
      <th scope="col">Estimated arrival date</th>
      <th scope="col">Amount</th>
      <th scope="col">Period</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td data-label="Account">Visa - 3412</td>
      <td data-label="Really freaking long div magic">04/01/2016</td>
      <td data-label="Amount">$1,190</td>
      <td data-label="Period">03/01/2016 - 03/31/2016</td>
    </tr>
    <tr>
      <td scope="row" data-label="Account">Visa - 6076</td>
      <td data-label="Due Date">03/01/2016</td>
      <td data-label="Amount">$2,443</td>
      <td data-label="Period">02/01/2016 - 02/29/2016</td>
    </tr>
    <tr>
      <td scope="row" data-label="Account">Corporate AMEX</td>
      <td data-label="Due Date">03/01/2016</td>
      <td data-label="Amount">$1,181</td>
      <td data-label="Period">02/01/2016 - 02/29/2016</td>
    </tr>
</tbody>
</table>

The column headers are assigned using the data-label attribute in CSS, which allows me to style large tables without manually adding the data-label for every single cell in the HTML. I am exploring ways to automatically pull the th values into the data-label attribute using JavaScript. Is this feasible?

Answer №1

Would you like to transform the table from its current format:

| Account | Estimated arrival date | Amount | Period |
| ------- | ---------------------- | ------ | ------ |
|    1234 |             03/15/2001 |  $1.00 |    3rd |
|    1235 |             04/21/2002 | $12.00 |    4th |
|    4594 |             11/11/2011 | $45.00 |    2nd |

To this new format?:

-----------
Account: 1234
Estimated Arrival Date: 03/15/2001
Amount: $1.00
Period: 3rd
-----------
Account: 1235
Estimated Arrival Date: 04/21/2002
Amount: $12.00
Period: 4th
-----------
Account: 4594
Estimated Arrival Date: 11/11/2011
Amount: $45.00
Period: 2nd
-----------

UPDATE Here is a code snippet for your reference:

function toggle() {
  var table = document.querySelector('.my-table');
  table.classList.toggle('show-thin');
}
.table {
  border-collapse: collapse;
  display: inline-table;
}

.tr {
  display: table-row;
}

.th, .td {
  display: table-cell;
  border: 1px solid #555;
  padding: 3px 6px;
}

.th {
  background-color: #ddd;
  font-weight: bold;
  text-align: center;
}

.td {
  text-align: right;
}

.my-table.show-thin {
  display: block;
}

.show-thin .tr {
  border-bottom: 1px solid black;
  display: block;
  margin-bottom: 2px;
  padding-bottom: 2px;
}

.show-thin .td {
  border: none;
  display: block;
  padding: 0;
  text-align: left;
}

.show-thin .td:before {
  content: attr(title) ':';
  display: inline-block;
  font-weight: bold;
  padding-right: 5px;
}

.show-thin .thin-hide {
  display: none;
}
<button onclick="toggle()">Toggle</button>
<hr/>
<div class="my-table">
<div class="tr thin-hide">
  <span class="th">Account</span>
  <span class="th">Estimated arrival date</span>
  <span class="th">Amount</span>
  <span class="th">Period</span>
</div>
<div class="tr">
  <span class="td" title="Account">1234</span>
  <span class="td" title="Estimated Arrival Date">03/15/2001</span>
  <span class="td" title="Amount">$1.00</span>
  <span class="td" title="Period">3rd</span>
</div>
<div class="tr">
  <span class="td" title="Account">1235</span>
  <span class="td" title="Estimated Arrival Date">04/21/2002</span>
  <span class="td" title="Amount">$12.00</span>
  <span class="td" title="Period">4th</span>
</div>
<div class="tr">
  <span class="td" title="Account">4594</span>
  <span class="td" title="Estimated Arrival Date">11/11/2011</span>
  <span class="td" title="Amount">$45.50</span>
  <span class="td" title="Period">2nd</span>
</div>
</div>

This demonstration showcases how utilizing a class can alter values from a tabular layout to a lined format. While it can also be achieved with a media query, the class method provides an easier visualization.

The key lies in assigning the title attribute to each cell and then using CSS to reveal the title when in "thin" mode.


https://i.stack.imgur.com/Wealz.gif

The image depicts the wide mode appearance of the table


https://i.stack.imgur.com/fAbvk.gif

While this image illustrates the thin mode view


Upon comparing both images, it's evident that the standard table format uses "Estimated arrival date" where only the first letter is capitalized, while the thin version employs "Estimated Arrival Date" with all words capitalized. This differentiation signifies the origin of the respective values.

In wide mode, the header is sourced from here:

<div class="tr thin-hide">
  <span class="th">Account</span>
  <span class="th">Estimated arrival date</span>
  <span class="th">Amount</span>
  <span class="th">Period</span>
</div>

Conversely, in thin mode, the header information stems from the title attribute.

It should be noted that attempting to utilize <table>, <tr>, <th>, and <td> tags will not yield the desired outcome.

Answer №2

This jQuery snippet copies the attribute "data-label" from TH to TD in a table.

$('table th').each(function(i,elem) {
  var num = i + 1;
  $('table td:nth-child(' + num + ')').attr('data-label', $(elem).text());
});

Answer №3

Here is my jQuery solution that effectively addresses table cells without colspans:

$('.myDiv table').each(function (index, value) {
    var headerCount = $(this).find('thead th').length;

    for (i = 0; i <= headerCount; i++) {
        var headerLabel = $(this).find('thead th:nth-child(' + i + ')').text();

        $(this).find('tr td:not([colspan]):nth-child(' + i + ')').replaceWith(
            function () {
                return $('<td data-label="' + headerLabel + '">').append($(this).contents());
            }
        );
    }

});

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

What is the best way to save information from an ng-repeat loop into a variable before sending it to an API?

My goal is to store the selected value from ng-repeat in UI (user selection from dropdown) and assign it to a variable. function saveSelection() { console.log('inside function') var postToDatabase = []; vm.newApplicant.values ...

PHP: When MySQL is not returning results and an undefined variable is causing issues

Currently, I am engaged in a project where I need to fetch some data from the database and display it within a form. Although my SQL query seems correct when reviewed in the SQL log, MySQL is not returning any results. I am seeking assistance on how to ret ...

Accessing Data from Nested PHP Array in Javascript

My current situation is this: I have a MYSQL database that consists of two fields: 'ID' and 'string'. The 'string' field stores serialized arrays. To extract the data back, I utilize the following PHP code: $result = mysql_q ...

Tips for using the identical function on matched elements

I am working on a code where I want each textbox input to change its corresponding image. The function is the same for all partners in the list (txt & img). I have looked around and found some similar posts, but I am struggling to make the function wor ...

send document through ajax

Having some trouble with this task. Here is what I've managed to put together so far: <input id="newFile" type="file"/> <span style="background-color:orange;" onClick="newImage()">HEYTRY</span> I know it's not much progress. ...

Trigger a fixed bottom bar animation upon hover

I have a bar fixed to the bottom of the browser that I want to hide by default. When a user hovers over it, I want the bar to be displayed until they move their cursor away. <!doctype html> <html> <head> <meta charset="utf-8"> &l ...

What methods do publications use to manage HTML5 banner advertisements?

We are working on creating animated ads with 4 distinct frames for online magazines. The magazines have strict size limits - one is 40k and the other is 50k. However, when I made an animated GIF in Photoshop under the size limit, the image quality suffered ...

Spinning an object using JQuery

I am currently working on a project to test my skills. I have set up a menu and now I want to customize it by rotating the icon consisting of three vertical lines by 90 degrees every time a user clicks on it. This icon is only visible on smartphones when t ...

Is it possible to update a Rails element using an AJAX request?

I've delved into a plethora of information regarding Rails, AJAX, and 5.1 Unobtrusive Javascript. It provides insight on how to handle AJAX calls in Rails with a .js file, for example. However, my goal isn't to serve up an entire .js file; rathe ...

Unable to transfer information from the Parent component to the Child component

Can you help me solve this strange issue? I am experiencing a problem where I am passing data from a parent component to a child component using a service method that returns data as Observable<DemoModel>. The issue is that when the child component ...

Node: Sending JSON Values in a POST Request

I am currently working with the index.js file below: var Lob = require('lob')('test_6afa806011ecd05b39535093f7e57757695'); var residence = require('./addresses.json'); console.log(residence.residence.length); for (i = 0; i ...

Removing data from the controller with JQUERY AJAX in a Spring MVC application

Could someone assist me with this issue? I am trying to implement ajax and sweetalert.js using the following repository: So far, everything is working well when I use onclick = "" to call my function. However, I need guidance on how to properly utilize th ...

Problem arises with table nth-child selector following the addition of grid-gap

Our current table looks like this: The first row has a background color and the second row is white - which is correct. Now I would like to align the attributes to the right. I added the following code to the table: .table-wrapper tbody { font-size: ...

What is the best way to retrieve data from a fetch request within a GET function?

It seems like a simple issue, but I'm struggling to retrieve information from my "body" when utilizing the get method. I've experimented with various approaches to extract the data, but nothing seems to work. Any guidance would be greatly appreci ...

Using the ESNEXT, Gutenberg provides a way to incorporate repeater blocks that

If you're like me, trying to create your own custom Gutenberg repeater block with a text and link input field can be quite challenging. I've spent hours looking at ES5 examples like this and this, but still feel stuck. I'm reaching out for ...

Unable to access property 'map' of undefined - having trouble mapping data retrieved from Axios request

When working with React, I have encountered an issue while trying to fetch data from an API I created. The console correctly displays the response, which is a list of user names. However, the mapping process is not functioning as expected. Any insights or ...

I am attempting to retrieve the initial three results from my MySQL database using Node.js, but I keep encountering an error

Below is the code I am currently using: con.query('SELECT * FROM tables', function(err, results) { if (err) throw err console.log(results[0].rawname) for(var i= 0; i <= 3; i++) { ...

Learn how to iterate over an array and display items with a specific class when clicked using jQuery

I have an array with values that I want to display one by one on the screen when the background div is clicked. However, I also want each element to fade out when clicked and then a new element to appear. Currently, the elements are being produced but th ...

Removing items from a list in a Vue.js application

I've encountered an issue with my code. I'm attempting to remove a "joke" from a list, but it consistently removes the joke that was inputted before the one I'm actually trying to delete. I'm struggling to identify what mistake I might ...

Is it considered acceptable to include paragraph elements within a heading tag in HTML5 (such as putting a <P> inside a <H1

Are paragraph elements allowed inside header tags in HTML5? Put simply, is this markup acceptable in HTML5? What are the implications of using it? <h1> <p class="major">Major part</p> <p class="minor"& ...