Search code examples
jquerycssmedia-queriescol

Responsive tables: show thead elements' content in corresponding tds


I have tables similar to this simplified version:

<table>
    <thead>
        <tr><th></th>
            <th>1st sg.</th><th>2nd</th><th>3rd...</th>
        </tr>
    </thead>
    <tbody>
        <tr><th>Present</th>
            <td>sum</td><td>es</td><td>est...</td>
        </tr>
        <tr><th>Perfect</th>
            <td>fui</td><td>fuisti</td><td>fuit...</td>
        </tr>
    </tbody>
</table>

And they do become quite wide. So I display: block all table elements, aside from thead which is display:none, Semantic UI style.

Which works pretty well as is. But I still would the content from the ths of thead to be still noticeable.

I think of using jQuery and dynamically adding an attribute called col or data-col, as can be seen started in this JsFiddle.

The dynamically created code would than be similar to the following:

<tbody>
    <tr>
        <th>Present</th>
        <td data-col="1st sg.">sum</td>
        <td data-col="2nd">es</td>
        <td data-col="3rd">est</td>
    </tr>
</tbody>

So my technical question is the following:

How can I dynamically get the content from a thead's th elements, and distribute said content to all tds of the same column as an attribute?

Other solutions are appreciated as well!


Solution

  • Here is a javascript function. See if this helps

        function td_col()
        {
            var table = $('table');
            table.find('tbody tr').each(function(){
                $(this).find('td').each(function(i){ 
                   $(this).attr('data-col', table.find('thead tr th:eq('+(i + 1)+')').html());
                })
            })
        }
    

    CSS Update :

            @media(max-width:470px) {
            td:before {
                float:right;
                content:attr(data-col); //Removed the brackets.
            }
        }
    

    Fiddle