Can the tooltip on c3 charts be modified dynamically?

Creating a c3 chart involves defining various properties, including a tooltip. Here is an example:

generateData = () => {
  const x = randomNR(0, 100);
  const y = randomNR(0, 100);
  const together = x + y;

  return {
    data: {
      columns: [
        ['data1', x],
        ['data2', y],
      ],
      type: 'donut',
    },
    tooltip: {
      format: {
        value: function() {
          return `${x} + ${y} = ${together}`
        }
      }
    },
    donut: {
      title: `Tooltip not getting updated`
    }
  }
};

After generating the chart, only the new data property can be loaded. Is it possible to update the tooltip as well? For example: https://plnkr.co/edit/8PrbjVqhS9BBYpSbZmkM?p=preview

In the provided case, updating the data results in incorrect values being displayed in the tooltip.

Answer №1

Consider trying out this alternate approach:

function generateRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

function createChartUpdater() {
  let xValue;
  let yValue;
  let totalValue;
  return () => {
    xValue = generateRandomNumber(0, 100);
    yValue = generateRandomNumber(0, 100);
    totalValue = xValue + yValue;
    return {
      data: {
        columns: [
          ['data1', xValue],
          ['data2', yValue],
        ],
        type: 'donut',
      },
      tooltip: {
        format: {
          value: function() {
            return `${xValue} + ${yValue} = ${totalValue}`
          }
        }
      },
      donut: {
        title: `Tooltip update issue`
      }
    }
  };
}

const chartUpdater = createChartUpdater();

const newChart = c3.generate({
  bindto: '#chart',
  ...chartUpdater()
});

setTimeout(function() {
  // HOW TO CHANGE THE TOOLTIP HERE?
  newChart.load(chartUpdater().data);
}, 2500);

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

The android webview is having trouble loading HTML that includes javascript

I have been attempting to showcase a webpage containing HTML and JavaScript in an android webview using the code below. Unfortunately, it doesn't seem to be functioning properly. Can someone provide assistance? Here is the code snippet: public class ...

Parsing JSON in an Express application

I have developed a small application to test a larger one that I am currently working on. The small application reads data from a CSV file and then attempts to send this data to my API endpoint using POST requests. This is necessary as I need to send a lar ...

What are the steps to set up Redis Store in my production environment?

I am currently in the process of setting up Redis as a session store, but for some reason it's not functioning properly. I have integrated passport.js and express-flash, however when I attempt to run the current Redis setup, it fails to work: var ses ...

What is the most effective method for grouping state updates from asynchronous calls in React for efficiency?

After reading this informative post, I learned that React does not automatically batch state updates when dealing with non-react events like setTimeout and Promise calls. Unlike react-based events such as onClick events, which are batched by react to reduc ...

Substitute dynamic Angular expressions with fixed values within a string

Inside my angular controller, I am defining a stringTemplate containing expressions like "{{data.a}} - {{data.b}}". Along with that, I have an object named data with values {a: "example1", b: "example2"}. My goal is to find a way to replace the dynamic ex ...

More efficient methods for handling dates in JavaScript

I need help with a form that requires the user to input both a start date and an end date. I then need to calculate the status of these dates for display on the UI: If the dates are in the past, the status should be "DONE" If the dates are in the future, ...

Group records in MongoDB by either (id1, id2) or (id2, id1)

Creating a messaging system with MongoDB, I have designed the message schema as follows: Message Schema: { senderId: ObjectId, receiverId: ObjectId createdAt: Date } My goal is to showcase all message exchanges between a user and other users ...

In what ways can you toggle the visibility of table rows and data dynamically with the onchange event in HTML?

I'm dealing with an HTML code that can dynamically change table data based on user selection. Here's the snippet of my HTML code: Select an option: <select name='set' id="set" class="selectpicker" onchange='displayFields(this. ...

Ways to verify and incorporate https:// in a URL for a MEAN Stack application

When extracting the URL from API data, my code looks like this: <div class="row copy-text"> <a href="{{copy.Url}}" target="_blank" style="text-decoration: underline !important;">{{copy.Title}}</a> </div> I am interested in ve ...

Is it better to have Angular and Laravel as separate applications or should Laravel serve the Angular app?

I have a new project in the works, aiming to create a large SAAS application. Although I come from a CakePHP background, I've decided to use Laravel and Angular for this venture. As I navigate through unfamiliar territory with these technologies, I a ...

The Ajax response is not providing the expected HTML object in jQuery

When converting HTML data from a partial view to $(data), it's not returning the jQuery object I expected: console.log($(data)) -> [#document] Instead, it returns this: console.log($(data)) -> [#text, <meta charset=​"utf-8">​, #text, < ...

Using AngularJS Material's mdDialog to show locally stored data in a template

In the controller, the section responsible for spawning mdDialog appears as follows: $scope.removeAttendee = function(item) { console.log(item); $mdDialog.show({ controller: DialogController, templateUrl: 'views/removeMsg.tm ...

The Web Browser is organizing CSS elements in an alphabetized sequence

map.css({ 'zoom': zoom, 'left': map.width()/(2*zoom) - (point[0]/100)*map.width(), 'top': map.height()/(2*zoom) - (point[1]/100)*map.height() Upon observation, it appears that Chrome adjusts the map zoom first be ...

The objects-to-csv module encountered an error: fs.existsSync is not a valid function for this

"TypeError: fs.existsSync is not a function" Whenever I try to create a CSV file and input some data into it, this error message pops up. const objectstocsv = require('objects-to-csv'); export default { data () { return { ...

Troubleshooting URL Problems with Node.js Search and Pagination

My results page has pagination set up and the routes are structured like this: app.get("/results",function(req,res){ query= select * from courses where // this part adds search parameters from req.query to the sql query// Object.keys(req.query.search).for ...

The functionality of linear mode seems to be malfunctioning when using separate components in the mat-horizontal-stepper

In an effort to break down the components of each step in mat-horizontal-stepper, I have included the following HTML code. <mat-horizontal-stepper [linear]="true" #stepper> <mat-step [stepControl]="selectAdvType"> <ng-template matStep ...

What is preventing me from loading js and css files on my web pages?

I have developed a web application using SpringMVC with Thymeleaf and I am encountering an issue while trying to load javascript and CSS on my HTML5 pages. Here is a snippet from my login.html: <html xmlns="http://www.w3.org/1999/xhtml"> <head&g ...

Ways to showcase a JavaScript popup on an Android WebView

Can a JavaScript popup window be opened on an Android web viewer that is coded similarly to this example from Google? If so, how can this be accomplished without closing the original background page and ensuring it resembles a popup as shown in the picture ...

Different ways to notify a React/Next.js page that Dark Mode has been switched?

I am in the process of creating my first basic Next.js and Tailwind app. The app includes a fixed header and a sidebar with a button to toggle between dark and light modes. To achieve this, I'm utilizing next-theme along with Tailwind, which has been ...

Hybrid application: Manipulate HTTP user agent header using AngularJS

I am currently developing a hybrid app using Cordova and Ionic. My current challenge involves making an HTTP request to access a server where I need to modify the user agent of the device in order to pass a secret key. $http({ method: 'GET&a ...