I have tables which requires different styles for large and small displays. I dont want to set the breakpoint for the the different CSS with a media query as different tables will require the breakpoint to be at different widths, depending on the tables content.
Ive decided to use javascript to detect when the table is wider than its containing div, and at that point add a class so that the small display CSS is applied. In my code below ive used the window resize event for demonstrative purposes, on my site I will use the document ready and window size changes events.
This works fine however there will be a flash on the screen for small devices as the table will be too large on window load, at which point the javascript will trigger and the small CSS will 'fix' the layout. Is there a way to avoid this flash and have a mobile first approach?
Im making a mobile website (only for phones and tablets) and 90% of my traffic is smaller devices, so I would like to optimize the experience for them.
<div>
<table style="width:60%" class="reference">
<tbody>
<tr>
<th>Firstname-Heading</th>
<th>Lastname-Heading</th>
<th class="mobile-hide">Points-Heading</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td class="mobile-hide">50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
<tr>
<td>Adam</td>
<td>Johnson</td>
<td>67</td>
</tr>
</tbody></table>
</div>
td, th {
white-space: nowrap;
word-wrap: normal;
}
div {
width: 50%;
overflow-x: auto;
}
table.small {
font-size: 0.5em;
}
table.small .mobile-hide {
display: none;
}
$(window).resize(function(){
var tableWidth = $("table").width();
console.log("tableWidth ", tableWidth);
var divWidth = $("div").width();
console.log("divWidth ", divWidth);
if (tableWidth > divWidth) {
$("table").addClass("small");
} else {
$("table").removeClass("small");
}
});