DaviDeMo
DaviDeMo

Reputation: 117

Chart.js custom tooltipTemplate index

I have this chart made with Chart.js.

var data = {
  labels: ["", "", "", "2015-08-28", "2015-08-29", "2015-08-30", "2015-08-31", ],
  websites: ["", "", "", "gamesoutletCrawler", "gamesoutletCrawler", "G2PLAY", "instantgaming", ],
  datasets: [{
    label: "Best price last 7 days",
    fillColor: "rgba(220,220,220,0.2)",
    strokeColor: "rgba(220,220,220,1)",
    pointColor: "rgba(220,220,220,1)",
    pointStrokeColor: "#fff",
    pointHighlightFill: "#fff",
    pointHighlightStroke: "rgba(220,220,220,1)",
    data: [0, 0, 0, 34.5, 36.8, 37.3, 37.99, ]
  }]
};

window.onload = function() {
  var ctx = document.getElementById("chartkeys").getContext("2d");
  window.myLine = new Chart(ctx).Line(data, {
    responsive: true,
    tooltipTemplate: "<%= data.websites[idx] %>",
    scaleLabel: "<%= Number(value).toFixed(2).replace('.', ',') + ' €'%>"
  });
}

On my tooltip template, I want to use values from data.websites but I don't know how to pass in the index for my tooltip array. This is not working:

<%= data.websites[idx] %>

idx is wrong, it's not the index the system is using. Any idea what I have to write here to show the index tooltip when you hover on the graph?

If I write <%= data.websites %>, it's showing me all the websites in the array, not the one hovered.

Upvotes: 1

Views: 1441

Answers (1)

potatopeelings
potatopeelings

Reputation: 41065

You can use a function instead of a template string

...
tooltipTemplate: function (d) {
    return data.websites[data.labels.indexOf(d.label)]
},
...

Note that this requires the labels to be unique, or if there are duplicate labels that it not matter which one is active (for instance, in your data, the first 3 labels are the same but that won't cause any problems because the first 3 entries in the websites array too are the same. If they were different this method will not work)

Upvotes: 3

Related Questions