Simple Responsive Table Solution for Mobile using jQuery


2 minute read

Listen to article
Audio is generated by DropInBlog's AI and may have slight pronunciation nuances. Learn more

So far I've found all the proposed solutions for dealing with wide tables on mobile to be a bit cumbersome and just not that great. Then I had the idea of wrapping the table in a div and just using overflow to make it scroll sideways without breaking the layout.

Turns out I wasn't the only one.. a quick search yielded this post over at Creative Code. The only thing I didn't really like about it is that it doesn't apply the wrapper on the fly. I don't like to add extra markup when I don't have to, especially when it's not even for all users. So I decided to make a tweak to apply the wrapper on the fly with jquery. Here are some examples in action (see the Plans table)

jQuery

$(document).ready(function(){ 
// Mobile tables
if ($(window).width() < 980){
$("table").wrap( '<div class="mogrid"></div>' );
}
});// end document.ready

I used 980 as my breakpoint as that is the width of my largest desktop size, but you could set this to whatever you want. Also if you didn't want to do all tables you could replace $("table") with something identifying the particular tables you want to effect. Maybe like: $("table.datagrid")

CSS

.mogrid {overflow-y:auto;-webkit-overflow-scrolling: touch;}

That's it! On the Creative Code example they use overflow-y:scroll; Which I replaced with overflow-y:auto; as that will only allow scrolling when needed opposed to all the time. Also big hat tip to them for the -webkit-overflow-scrolling: touch; That makes the scrolling feel great on iPhone.

« Back to Blog