Responsive DataTable in Bootstrap 5 automatically hides columns to ensure optimal display on different

Is it possible to create a responsive table using DataTable 1.13.4 and Bootstrap 5.2.3? I encountered an issue while testing the table on a mobile device (using Firefox, not an actual device) where a small horizontal scrollbar appears, causing some columns to disappear.

Following the guidelines in the official DataTable documentation, I installed two dependencies via Yarn:

  • datatables.net-bs5 (DataTable for Bootstrap 5)
  • datatables.net-responsive-bs5 (Plugin enabling responsiveness for Bootstrap 5)

I am aware of the need to add the Bootstrap 5 table-responsive class before defining the table, but I also want to retain pagination and filtering. To achieve this, I included the dom option in my JavaScript code when instantiating the DataTable object (

dom: 'f<"table-responsive"t>...
)

View the result on a desktop screen
View the result on a mobile screen

Although the screenshots may not show it, a small horizontal scrollbar appears on both desktop and mobile screens. On mobile devices, this scrollbar is so small (about 5/10 pixels) that it hides the Description column, which is visible on desktop screens.

Here is my JavaScript file:

import {Controller} from '@hotwired/stimulus';

import DataTable from "datatables.net-bs5";
import "datatables.net-responsive-bs5";

export default class extends Controller {
    connect() {
        new DataTable('#tableMenu', {
            pageLength: 5,
            responsive: true,
            dom: 'f<"table-responsive"t><"row"<"col-sm-12 col-lg-6 mb-3 mb-lg-0"i><"col-sm-12 col-lg-6 d-lg-flex justify-content-lg-end"p>>'
        });
    }
}

And here is my HTML file:

<table id="tableMenu" class="table table-striped">
    <thead>
    <tr>
        <th></th>
        <th>Title</th>
        <th>Price</th>
        <th>Description</th>
    </tr>
    </thead>
    <tbody>
    {% for menu in menus %}
        <tr>
            <td>
                <a href="{{ path('app.admin.menu.edit', {'id': menu.id}) }}" class="btn btn-primary">
                    <i class="fa fa-pen" style="font-size: 10px;"></i>
                </a>
                <button type="button"
                        id="delete-menu"
                        data-delete-url="{{ path('api.menu.delete', {'id': menu.id}) }}"
                        class="btn btn-danger">
                    <i class="fa fa-xmark" style="font-size: 10px;"></i>
                </button>
            </td>
            <td>{{ menu.title }}</td>
            <td>{{ menu.price / 100 }}€</td>
            <td>{{ menu.description }}</td>
        </tr>
    {% endfor %}
    <tfoot>
    <tr>
        <th></th>
        <th>Title</th>
        <th>Price</th>
        <th>Description</th>
    </tr>
    </tfoot>
</table>

Thank you all for your assistance! 🫶

Answer №1

After extensive research, I have discovered a solution.

I have maintained the original code but simply added two classes to my <tr> element:

  • overflow-hidden
  • text-nowrap

As a result, my JavaScript file remains unchanged.
Here is how my HTML file now looks:

<table id="tableMenu" class="table table-striped">
    <thead>
    <tr>
        <th></th>
        <th>Titre</th>
        <th>Prix</th>
        <th>Description</th>
    </tr>
    </thead>
    <tbody>
    {% for menu in menus %}
        <tr class="overflow-hidden text-nowrap">
            <td>
                <a href="{{ path('app.admin.menu.edit', {'id': menu.id}) }}" class="btn btn-primary">
                    <i class="fa fa-pen" style="font-size: 10px;"></i>
                </a>
                <button type="button"
                        id="delete-menu"
                        data-delete-url="{{ path('api.menu.delete', {'id': menu.id}) }}"
                        class="btn btn-danger">
                    <i class="fa fa-xmark" style="font-size: 10px;"></i>
                </button>
            </td>
            <td>{{ menu.title }}</td>
            <td>{{ menu.price / 100 }}€</td>
            <td>{{ menu.description }}</td>
        </tr>
    {% endfor %}
    <tfoot>
    <tr>
        <th></th>
        <th>Titre</th>
        <th>Prix</th>
        <th>Description</th>
    </tr>
    </tfoot>
</table>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Date.now() twice within a single declaration of an object

In this scenario, consider the object var o = {a:Date.now(), b:Date.now()}. Would it be safe to assume that o.a === o.b is consistently true? (My focus is particularly on Node.JS.) ...

Constructor not executing when using Object.create

Attempting to instantiate a class within a static method, I am using Object.create(this.prototype), which appears to be functioning correctly. Nonetheless, when I check the console, my property items is showing as undefined. The base class called model lo ...

Add an array as a nested child within another array using node.js and JavaScript

Description: I execute a MySQL query to retrieve rows from a table > connection.query(q2,function(err,rows){...} Assuming the rows have a structure like {id:",,,", time:"..." etc:"cc"} For each row, I then query another table to fetch additional dat ...

"Sending an array in a POST request using Javascript and processing it on the server

I am trying to use ajax to send an array. Let's say the array looks like this: var anotherOne = 'anotherOneData'; var documents = ['banana', 'apple', 'monkey']; I successfully sent both a normal value and an a ...

What is the best way to add JavaScript sources to the startup.cs of AspNetCore?

Is there a simple way to link JS sources from a JS project located at "JSProj/src/main.js" and "JSProj/package.json" to execute in "AspNetCoreProj/startup.cs"? How can I ensure that when I run the ASP, my controller from &quo ...

The attempt to run 'readAsBinaryString' on 'FileReader' was unsuccessful. The first parameter is not the expected type 'Blob'

I am currently working on parsing an xls file. You can find the file by clicking on the following link: However, I am encountering an error that says: 'Failed to execute 'readAsBinaryString' on 'FileReader': parameter 1 is not of ...

Experiencing inaccuracies in Magento's item validation process when checking the quantity of items being added to the cart

Upon entering a text string in the quantity field of the "Add to Cart" input box, Magento does not display an error message but instead considers it as a quantity of "1". Is there a way to modify this behavior and have the validation system mark strings ...

Is there a more efficient method to choose specific UV coordinates from a texture for presentation on a sprite using three.js?

I've got a texture sheet that contains various game HUD elements UV packed together in one texture. Currently, I find myself having to create a clone() of the texture for each individual part of the GUI, then create a material using this texture in o ...

Automated file uploading with AJAX on Firefox

After inserting a row into the database, I want to automatically upload a PDF/XML file with no user involvement. The script should be able to identify the filename and location of the file. Is there a method to achieve this task? Share your ideas in the a ...

Tips for choosing the following row in an Angular user interface grid

How can I deselect the currently selected row and select the one that follows it by clicking a button? I am using AngularHotkeys.js for this purpose. It gets even more complicated because I can sort the table with different columns. It would be helpful to ...

Error encountered while using VueJS: The Register component was not recognized as a

Encountering issues with the registration component in VueJS. I acquired the component from https://github.com/wanxe/vue-button-spinner via npm install. Subsequently, I integrated the code into my Laravel 5.5 app.js file. The contents of my app.js: requi ...

Implementing Vue modal within a Laravel 5.2 foreach loop

I am facing a challenge with my Laravel blade template that uses a foreach loop to create a table with data. Each row has a link that triggers a modal when clicked. However, the issue is that clicking on any link activates the modal for every row instead o ...

Tips for including MUI icon within a list displayed on a map:

Initially, I brought in the AccountCircle Icon from MUI: import { AccountCircle } from '@mui/icons-material'; Then, I utilized styled to customize the icon: const UserIcon = styled(AccountCircle)({ margin: '0px 0px 0px 0px', }); My ex ...

Customize a web template using HTML5, JavaScript, and jQuery, then download it to your local device

I am currently working on developing a website that allows clients to set up certain settings, which can then be written to a file within my project's filesystem rather than their own. This file will then have some parts overwritten and must be saved ...

Using Javascript, dynamically animate the text in the hero unit with fading in and out effects

I currently have a "Hero" unit with the following code: <div class="hero-unit"> <div class="container"> <h1>Dapibus Euismod Mollis</h1> <p>Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis ...

Error message stating that there is no property 'collection' in Firestore when using Firebase v9 modular syntax in Firebase Firestore

Working on a React application that makes use of Firebase Firestore for handling database operations, I recently upgraded to Firebase version 9 and adopted the modular syntax for importing Firebase services. Nevertheless, when attempting to utilize the co ...

Filtering DataGrid columns with an external button in Material-UI: A step-by-step guide

Imagine having a datagrid table structured as shown below: import * as React from 'react'; import { DataGrid, GridToolbar } from '@mui/x-data-grid'; import { useDemoData } from '@mui/x-data-grid-generator'; const VISIBLE_FIEL ...

CrossBrowser - Obtain CSS color information

I'm attempting to retrieve the background color of an element: var bgcolor = $('.myclass').first().css('background-color') and then convert it to hex function rgbhex(color) { return "#" + $.map(color.match(/\b(\d+ ...

Adjust the height of a div in JQuery to fit new content after specifying a height previously

I have a division element with an initial height of 0 and opacity set to zero, its overflow is hidden, and it contains some content. <div style='height: 0px; opacity: 0px; display: none; overflow: hidden; border: 1px solid #000;' id='myd ...

How to toggle the visibility of a menu using uibootstrap and angularjs?

First Second Objective: My goal is to achieve a functionality similar to the screenshots above. For instance, when I click on the "Search with a list of items" link, the div should expand like in the Second screenshot and collapse when clicking on the sa ...