Binary I.T. Solutions, Inc.

Make a HTML Table Responsive with a simple script.

Using Jquery you can tell any table on a webpage to show a table in a easy to read responsive format using Jquery and a simple CSS Media call.

Step 1.  Make sure you call Jquery

Example:  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Step 2.  Make sure all table headers are called as TH not TD.

Step 3.  Insert the Following Javascript:

 

<script type="text/javascript">
$(function() {

$('table').each(function() {

var head_col_count = $(this).find('th').size();
for ( i=0; i <= head_col_count; i++ ) {

var head_col_label = $(this).find('th:nth-child('+ i +')').text();
$(this).find('tr td:nth-child('+ i +')').attr('data-th',head_col_label );

}

})

});
</script>

 

Step 4.  Add Media CSS:

<style>
table {
width:100%;
border-collapse:collapse;
}

@media only screen and (max-width:550px) {

table, thead, tbody, th, td, tr {display: block;}
th {display:none;}
tr:first-child {
border-top:none;
margin-bottom:0;
}
tr {
border-top:1px solid #ccc;
border-right:1px solid #ccc;
border-left:1px solid #ccc;
margin-bottom:5px;
}
td {
border: none;
border-bottom: 1px solid #ccc;
position: relative !important;
padding-left: 50% !important;
white-space: normal;
text-align:right !important;
}
td:before {
padding-right: 10px;
white-space: nowrap;
text-align:left;
font-weight: bold;
}
td:before {
content: attr(data-th)":";
position:absolute;
left:5px;
}

}
</style>

This script will work even if there is multiple tables on the same page.  I also added a JFiddle Page so you can test it yourself:

http://jsfiddle.net/brookh/wp1zhLe2/2/

 

Join Our Mailing List

* indicates required

Powered by MailChimp

Service Spotlight

  • Search Engine Optimization

SEO (Search Engine Optimization) Every time you turn around, there’s something new you have to know about on the internet. Think about it, there was a time when you knew every song on every album and what every make and model was driving down the street. Well, those days are OVER. But we are here to help you with the internet.

Las Vegas Web Design and Las Vegas Marketing Services can find ways of optimizing your site, finding valuable links, getting you added successfully to Local listing tools like Google, Yahoo, MSN and much more. We can tailor make a plan for as little as $99.00 per month guarenteed. This also includes the management of your Pay Per Click Advertisements.

Read More About SEO

Member Login