Call or email today for a free consultation.
Mobile-responsive tables
- Mobile-responsive tables March 19, 2014 at 2:39 pm
- Contenteditable text editor in a web browser October 22, 2013 at 5:55 pm
- HTML CSS3 3D Panorama viewer with accelerometer and compass in the stock October 22, 2013 at 12:35 pm
- Circular rotation in Javascript October 22, 2013 at 10:13 am
- How to stroke text in Illustrator: A tutorial July 21, 2013 at 11:20 pm
- How I saved a client $60,000 (or, Where To Tap) July 21, 2013 at 9:21 pm
- How much does a website cost? July 21, 2013 at 8:21 pm
- Use htaccess to rewrite URLs with query strings July 21, 2013 at 7:22 pm
- Ian Tregillis web site July 21, 2013 at 3:04 pm
- Web design as an art form July 21, 2013 at 2:59 pm
When I was in the middle of making a site with a lot of product specifications, I needed a generic way to make all those tables responsive. A colleague of mine pointed me to Garrett Dimon's solution on CSS-Tricks.com, which hard-coded the table headings right in the CSS. But what to do if you don't know what they are until they are displayed on the page?
The answer is to loop through the table headers in Javascript and write out a scoped block that will dynamically generate the CSS you need to display those table headers correctly. My tweak looks like this:
$('.div_with_unique_id_and_tables').each(function () {
var tab = $(this);
var table = $('table', tab);
var th = $('th', table);
if (th.length != 0) {
var style = '<style>@media (max-width: 760px) {';
th.each(function (index) {
var cell = $(this);
style += '#' + tab.attr('id') + ' td:nth-of-type(' + (index + 1) + '):before { content: "' + cell.html() + '"; } ';
});
style += '}</style>'
tab.prepend(style)
}
});
The trick is in the ':nth-of-type()' selector: you can selectively apply that style to only that type. In this case, we're writing out the table header for that row into each data cell, which through CSS we've made into block-level elements instead. All I had to do was instead of hard-coding those table header values, write out each block of CSS on page load that dynamically inserts the table header html, whatever that is, into the mobile-responsive media query, scoped to the id of the table's parent div.
Easy!
Note: this doesn't work on older IE browsers. But if you're running one of those on your phone, you'e got bigger problems.
Comments