Bootstrap 3 responsive table alternative

Using bootstrap 3 to make a table responsive

by Duke Dinh

HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.0/bootstrap.min.js"></script>
<table class="table table-condensed table-bordered table-striped table-hover responsive">
    <tr>
        <th align="left">Header1</th>
        <th align="left">Header2</th>
        <th align="left">Header3</th>
    </tr>
    <tr>
        <td>alpha</td>
        <td>bravo</td>
        <td>charlie</td>
    </tr>
    <tr>
        <td>ALPHA</td>
        <td>BRAVO</td>
        <td>CHARLIE</td>
    </tr>
</table>

CSS

@import url('http://getbootstrap.com/dist/css/bootstrap.css');
 table.responsive {
    border-collapse: collapse;
}
@media only screen and (max-width: 760px), (min-device-width: 768px) and (max-device-width: 1024px) {
    table.responsive {
        width: 100%;
        min-width: 320px;
    }
    /* Force table to not be like tables anymore */
    table.responsive, table.responsive thead, table.responsive tbody, table.responsive th, table.responsive td, table.responsive tr {
        display: block;
    }
    /* Hide table headers (but not display: none;, for accessibility) */
    table.responsive th {
        position: absolute;
        top: -9999px;
        left: -9999px;
    }
    table.responsive tr {
        border: 1px solid #ccc;
    }
    table.responsive tr:nth-of-type(even) {
        background-color: #eee;
    }
    table.responsive td {
        /* Behave  like a "row" */
        border: none;
        border-bottom: 1px solid #eee;
        position: relative;
        padding-left: 50% !important;
    }
    table.responsive td:before {
        /* Now like a table header */
        position: absolute;
        /* Top/left values mimic padding */
        top: 6px;
        left: 6px;
        width: 45%;
        padding-right: 10px;
        white-space: nowrap;
    }
}

JavaScript

$(document).ready(function () {
    $("table.responsive").each(function () {
        var headers = [];
        $(this).find("th").each(function () {
            headers.push($(this).text().trim());
        });

        // Generate CSS string
        var css_str = "<style>@media only screen and (max-width: 760px), (min-device-width: 768px) and (max-device-width: 1024px) { ";
        var header, num;
        for (var i in headers) {
            header = headers[i].replace(/([\\"])/g, "\\$1").replace(/\n/g, " ");
            num = parseInt(i, 10) + 1;
            css_str += "table.responsive td:nth-of-type(" + num + "):before { content: \"" + header + "\"; }" + "\n";
        }
        css_str += " }</style>";
        $(css_str).appendTo("head");
    });
});