The functionality of Bootstrap DataTable Sparkline is compromised when the table is configured to be responsive

I am working with a Bootstrap DataTable that includes a sparkline in the last column. Here is the complete JavaScript code:

$(document).ready(function() {
  var groupColumn = 0;

  let table = $('#example').DataTable({
    //responsive: true,
    autoWidth: true,
    processing: true,
    ordering: true,
    scrollY: '50vh',
    scrollCollapse: true,
    paging: false,
    searching: true,

    ajax: {
      url: "api/ApartmentsAvailables",
      type: "GET",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
    },
    columnDefs: [{
        visible: false,
        targets: groupColumn
      },
      {
        targets: 7,
        render: DataTable.render.datetime('YYYY-MM-DDT00:00:00', 'MMMM D, YYYY', 'en'),
      },
      {
        responsivePriority: 1,
        targets: 0
      },
    ],
    order: [
      [groupColumn, 'asc']
    ],

    drawCallback: function(settings) {
      $('.sparkline')
        .map(function() {
          return $('canvas', this).length ? null : this;
        })
        .sparkline('html', {
          type: 'line',
          width: '250px'
        })

      var api = this.api();
      var rows = api.rows({
        page: 'current'
      }).nodes();
      var last = null;

      api
        .column(groupColumn, {
          page: 'current'
        })
        .data()
        .each(function(group, i) {
          if (last !== group) {
            $(rows)
              .eq(i)
              .before('<tr class="group" style="background-color:DarkGray; text-align:center;font-weight: bold; color:white;"><td  colspan="8">' + group + '</td></tr>');

            last = group;
          }
        })
    },
    columns: [

      {
        data: "building"
      },
      {
        data: "floor_Plan"
      },
      {
        data: "apt_Number"
      },
      {
        data: "rent"
      },
      {
        data: "bedrooms"
      },
      {
        data: "bathrooms"
      },
      {
        data: "sqft"
      },
      {
        data: "available_Date"
      },
      {
        data: 'prices',
        render: function(data, type, row, meta) {

          return type === 'display' ?
            '<span class="sparkline">' + data.toString() + '</span>' :
            data;
        }
      },
    ]
  });
  new $.fn.dataTable.FixedHeader(table);
  // Order by the grouping
  $('#example tbody').on('click', 'tr.group', function() {
    var currentOrder = table.order()[0];
    if (currentOrder[0] === groupColumn && currentOrder[1] === 'asc') {
      table.order([groupColumn, 'desc']).draw();
    } else {
      table.order([groupColumn, 'asc']).draw();
    }
  });
});

The issue arises when I activate responsive: true. The sparkline column gets hidden, and upon expanding the row to reveal the hidden columns, it displays the entire array of values instead of the sparkline.

It seems that the

drawCallback: function (settings) {
            $('.sparkline')
                .map(function () {
                    return $('canvas', this).length ? null : this;
                })
                .sparkline('html', {
                    type: 'line',
                    width: '250px'
                })

cannot be applied to a hidden column.

When the responsive option is disabled, the generated HTML for the td is:

<td>
    <span class="sparkline">
        <canvas style="display: inline-block; width: 250px; height: 21px; vertical-align: top;"
                width="250"
                height="21"/>
    </span>
</td>

With the responsive set to true:

<td style="display: none;"
    class="dtr-hidden">
    <span class="sparkline">3446,3446,3416,3416,3416,3546,3546,3546,3546,3546,3546,3561,3556,3551,3396,3396,3396,3346,3306,3306,3306</span>
</td>

I believe I need to somehow capture the click on the expand icon and then re-insert the canvas, but I am unsure how to accomplish this.

Answer №1

One solution is to utilize a specific event provided by the DataTables Responsive extension:

responsive-display

Whenever this event is triggered...

The details for a row are displayed, updated, or hidden.

For instance, you can insert the following code into your script and incorporate your sparklines functionality within the event handler:

table.on( 'responsive-display', function ( e, datatable, row, showHide, update ) {
    $('.sparkline')
      .map(function() {
        return $('canvas', this).length ? null : this;
      })
      .sparkline('html', {
        type: 'line',
        width: '250px'
      });
  } );

This will regenerate your sparkline based on the raw data.


Refer to the official documentation for a comprehensive list of events, API functions, and options supported by the Responsive extension.


Update

"unable to make it work..."

If it helps, here is a live demo:

// JavaScript code goes here
<!doctype html>
<html>
<head>
  <!-- Head section goes here -->
</head>

<body>

<div>
    <!-- DataTables table goes here -->
</div>

</body>
</html>

If you're missing the icons, simply click on the cell to toggle the data display. Additionally, I've disabled the setInterval function to prevent the display from resetting every 5 seconds.

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

What is the best way to obtain the inner ID with JQuery?

How can I assign values to inside id using JQuery? Sample code from controller.cs: public GroupModel Get() { IGroupTypeRepository groupTypeRepo = new GroupTypeRepository(); IGroupRepository groupRepo = new GroupRepository(); var model = new ...

Error: JSON at position 1 is throwing off the syntax in EXPRESS due to an unexpected token "

I'm currently utilizing a REST web service within Express and I am looking to retrieve an object that includes the specified hours. var express = require('express'); var router = express.Router(); /* GET home page. ...

Discover the #ID and apply AddClass through the URL in the Navigation Jquery

I am currently in the process of developing a website and I am looking to navigate from one link to another using IDs. Here is an example of what I am trying to achieve: Page Name: index.html <a href= "collection.html#rings">Rings</a> Page N ...

Turn off bodyparser when uploading files in Node.js

This query is quite similar to another one on Stack Overflow regarding how to disable Express BodyParser for file uploads in Node.js. The solution provided there was for Express3, but when tested with the updated Express 4, it didn't work as expected. ...

What is the best way to apply focus to a list element using Javascript?

I recently created code to display a list of elements on my webpage. Additionally, I implemented JavaScript functionality to slice the elements. Initially, my page displays 5 elements and each time a user clicks on the "show more" link, an additional 5 ele ...

The issue arising where the callback function fails to execute after making an AJAX POST request

Within my function, I have an AJAX call that I want to make reusable. When the AJAX call is successful, I need to callback a function. var ajaxPostCall = function(data , url ,callback){ // Return the $.ajax promise $.ajax({ data: data, dataType: ...

Traverse the JSON array in a loop

I am currently facing an issue with looping through a JSON array that I am passing to PHP. At this point, I am only passing one array and receiving the same array back from the PHP file. While I can loop through the data in JavaScript, I am encountering er ...

Issue with retrieving relative time using Moment.js - fromNow()

I want to utilize moment.js to display relative time fromNow(), but I am encountering an issue where the values are being rounded and showing higher durations instead of exact completion times. For example, moment().subtract('s',110).fromNow() / ...

What is the best way to address cookie issues while working on a full stack application that utilizes Vue and Express.js?

Developing a full stack application requires me to use Vue on port 5173 and Express on port 3000. One issue I face is the inability to store credentials in the frontend for backend communication during development. This challenge can be addressed by servin ...

Issue with exporting data from Datatables

I followed the instructions, and the Datatables export function worked perfectly in localhost, but when I tried it in Google Apps script, it didn't work. For more information about the issue, you can visit this link: DataTables TableTools buttons not ...

Local connections are successfully established with Socket.IO, however, external connections are experiencing difficulties

I'm a beginner in Node.js and currently working on a simple chat application. However, I have hit a roadblock. I've tried searching online and using various solutions, but I still can't seem to get it to work. If anyone could lend a hand, ...

What is the appropriate utilization of the await keyword within concise if-else statements in JavaScript?

Along with transitioning away from jQuery, my main focus is to make my code more efficient. In large scale enterprise applications, the excessive use of jQuery and JavaScript can become problematic. I have decided to switch back to vanilla JavaScript for ...

Sending a parameter to a different function (on a separate webpage)

At the start of my webpage, there are two radio buttons on the first page, each with its own value. Upon clicking a link to move to the second page, a for loop is activated to grab the value of the selected button. The script has been tested and works as e ...

Having trouble with the response function not functioning properly within an AJAX autocomplete

I have implemented an autocomplete feature using the jQuery UI plugin from http://jqueryui.com/autocomplete/#remote-jsonp. $("#city" ).autocomplete({ source: function( request, response ) { $.ajax({ url: 'index.php?secController= ...

select items using a dropdown menu in an Angular application

Let me describe a scenario where I am facing an issue. I have created an HTML table with certain elements and a drop-down list Click here for image illustration When the user selects in, only records with type in should be displayed Another image refere ...

Tips for troubleshooting a sass file that is not displaying changes in the browser

Currently working on my portfolio website using bootstrap and sass along with a theme kit. Initially, I attempted to implement a grid column style for the intro-section but had a change of heart and deleted the style. Surprisingly, every time I refresh my ...

Exploring the world of Node.js with fs, path, and the

I am facing an issue with the readdirSync function in my application. I need to access a specific folder located at the root of my app. development --allure ----allure-result --myapproot ----myapp.js The folder I want to read is allure-results, and to d ...

I prefer to avoid generating the document structure while parsing with JSOUP

Utilizing the Jsoup API to parse a section of HTML using the Jsoup.parse() method. However, during parsing, it includes the document structure in the HTML content. For Instance: <p><a href="some link">some link data</a> Some paragraph c ...

Creating HTML elements using Vue.js

Currently, I am facing an issue while attempting to render a template using the push mutation method. My goal is to push a section component, but instead of seeing the desired template content on my page, I am only getting the raw output of <vsection> ...

The Coinbase Pay application fails to compile properly due to a missing Babel loader

Currently, I am working on integrating the coinbase pay sdk into my project. Although I have successfully created a button utilizing their provided examples, I am encountering an issue during the build process which seems to be internal to their SDK. Spec ...