Making tables responsive using jQuery

Loading

Making Tables Responsive Using jQuery

Tables are essential components in web applications for displaying structured data. However, traditional HTML tables often lack flexibility, making them difficult to read on small screens. In this guide, we will discuss how to make tables responsive using jQuery, ensuring they adapt seamlessly to different screen sizes.


Why Do We Need Responsive Tables?

Before diving into the implementation, let’s understand why responsive tables are important:

  1. Better Readability: Large tables can be hard to navigate on mobile devices. Responsive tables improve user experience.
  2. Seamless User Interaction: Users don’t have to scroll horizontally, making data easier to analyze.
  3. Modern UI/UX Standards: Most websites follow a mobile-first approach, and responsive tables are crucial for modern web design.
  4. Cross-Device Compatibility: Ensures that tables are functional across desktops, tablets, and smartphones.

Approaches to Making Tables Responsive

There are several ways to make tables responsive using jQuery:

  1. Adding a Scrollable Container
  2. Stacking Columns for Small Screens
  3. Using DataTables Plugin
  4. Converting Tables to Cards on Small Screens
  5. Using jQuery for Dynamic Column Visibility

Let’s go through each of these approaches with detailed examples.


1. Making Tables Scrollable Using jQuery

A simple yet effective way to make tables responsive is by wrapping them inside a scrollable div.

Steps to Implement:

  1. Wrap the table inside a div with the class responsive-table.
  2. Use CSS to set overflow-x: auto for small screens.
  3. Use jQuery to dynamically add styles based on screen size.

Example Code

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Responsive Table</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .responsive-table {
            overflow-x: auto;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            padding: 10px;
            border: 1px solid #ddd;
            text-align: left;
        }
    </style>
</head>
<body>

    <div class="responsive-table">
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Phone</th>
                    <th>Address</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>John Doe</td>
                    <td>john@example.com</td>
                    <td>123-456-7890</td>
                    <td>New York, USA</td>
                </tr>
                <tr>
                    <td>Jane Smith</td>
                    <td>jane@example.com</td>
                    <td>987-654-3210</td>
                    <td>Los Angeles, USA</td>
                </tr>
            </tbody>
        </table>
    </div>

</body>
</html>

jQuery (Optional Enhancement)

$(document).ready(function() {
    if ($(window).width() < 768) {
        $(".responsive-table").css("overflow-x", "auto");
    }
});

How It Works?

  • If the screen width is less than 768px, jQuery applies overflow-x: auto to allow horizontal scrolling.

2. Stacking Table Columns Using jQuery

For a mobile-friendly layout, we can stack table rows as individual sections.

Implementation Steps:

  1. Use jQuery to rearrange table data into stacked sections.
  2. Apply CSS to format the table as a block layout.
  3. Use media queries to apply this only for small screens.

Example Code

CSS

@media screen and (max-width: 600px) {
    table, thead, tbody, th, td, tr {
        display: block;
    }
    thead tr {
        display: none;
    }
    tr {
        margin-bottom: 10px;
    }
    td {
        display: flex;
        justify-content: space-between;
        border-bottom: 1px solid #ddd;
    }
    td::before {
        content: attr(data-label);
        font-weight: bold;
    }
}

jQuery

$(document).ready(function() {
    $("table tbody tr td").each(function() {
        let index = $(this).index();
        let headerText = $("table thead th").eq(index).text();
        $(this).attr("data-label", headerText);
    });
});

How It Works?

  • Each td element gets a data-label attribute from the corresponding table header (th).
  • On small screens, td::before displays the data-label, making it readable.

3. Using DataTables Plugin for Responsive Tables

DataTables is a powerful jQuery plugin for making tables dynamic and responsive.

Steps to Implement:

  1. Include the DataTables CDN.
  2. Initialize the DataTable using jQuery.

Example Code

<link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>

<script>
$(document).ready(function() {
    $('table').DataTable({
        responsive: true
    });
});
</script>

Features of DataTables:
✔️ Searchable & Sortable
✔️ Pagination Support
✔️ Automatic Responsiveness


4. Converting Tables to Cards Using jQuery

For better mobile UX, we can transform tables into card-based layouts.

Steps to Implement:

  1. Hide the default table on mobile.
  2. Use jQuery to dynamically convert rows into card elements.
  3. Display the cards instead of a table.

Example jQuery Code

$(document).ready(function() {
    if ($(window).width() < 600) {
        $("table").hide();
        $("table tbody tr").each(function() {
            let name = $(this).find("td").eq(0).text();
            let email = $(this).find("td").eq(1).text();
            let phone = $(this).find("td").eq(2).text();
            let address = $(this).find("td").eq(3).text();
            
            let card = `<div class='card'>
                        <p><strong>Name:</strong> ${name}</p>
                        <p><strong>Email:</strong> ${email}</p>
                        <p><strong>Phone:</strong> ${phone}</p>
                        <p><strong>Address:</strong> ${address}</p>
                        </div>`;
            $(".responsive-table").append(card);
        });
    }
});

CSS for Cards

.card {
    border: 1px solid #ddd;
    padding: 10px;
    margin: 10px 0;
    background-color: #f9f9f9;
}

How It Works?

  • If the screen width is <600px, it hides the table and creates card views using jQuery.

By using jQuery and CSS, we can make tables fully responsive. We covered multiple approaches:

Scrollable Tables
Stacked Table Rows
DataTables Plugin
Table-to-Card Conversion

Implement the best method that fits your website’s design and user experience!

Leave a Reply

Your email address will not be published. Required fields are marked *