ezRtable

easy to Responsive Table

by Georgio Wan

HTML

<table class="table-ezr">
  <thead>
    <tr>
      <th>NAME</th>
      <th class="th-ezr">AGE</th>
      <th class="th-ezr">COUNTRY</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Georgio</td>
      <td class="td-ezr">27</td>
      <td class="td-ezr">Taiwan</td>
    </tr>
    <tr>
      <td>Carol</td>
      <td class="td-ezr">24</td>
      <td class="td-ezr">Taiwan</td>
    </tr>
  </tbody>
</table>

CSS

/*****************************************************/
/*********** ezRtable - Responsive table *************/
/** https://github.com/GeorgioWan/ezResponsiveTable **/
/*****************************************************/
@media screen and (max-width: 600px) {
  table.table-ezr thead { display: none; }
  table.table-ezr tbody td { 
    display: block; 
    padding: .6rem; 
    text-align: center;
  }
  table.table-ezr tbody tr td:first-child { 
    font-weight: bold;
    background: #34495E; 
    color: #fff;
  }
  table.table-ezr tbody tr td:first-child a{ 
    color: #1ABC9C;
  }
  table.table-ezr tbody tr .td-ezr:before { 
    content: attr(data-th); 
    font-weight: bold;
    width: 6rem;
    float: left;
    text-align: left;
  }
}

JavaScript

/*****************************************************/
/*********** ezRtable - Responsive table *************/
/** https://github.com/GeorgioWan/ezResponsiveTable **/
/*****************************************************/
function ezRtable(){
  if($('.table-ezr').length){
    var headertext = [],
    headers = document.querySelectorAll(".table-ezr .th-ezr"),
    tablebody = document.querySelector(".table-ezr tbody");
    
    for(var i = 0; i < headers.length; i++) {
      var current = headers[i];
      headertext.push(current.textContent.replace(/\r?\n|\r/,""));
    } 
    for (var i = 0, row; row = tablebody.rows[i]; i++) {
      var ht = 0;
      for (var j = 0, col; col = row.cells[j]; j++) {
        if ( col.className == "td-ezr" )
          col.setAttribute("data-th", headertext[ht++]);
      } 
    }
  }
}

$(document).ready(function() {  
  ezRtable();
});