Forgive me for my sometimes poor English. Dutch is my native language.
I've created a Chart.js linechart which shows me my energy usage reported by my main power smart meter. I got it almost working like the way I want, but there is one thing I can't manage to get it to work in a way I want because I don't understand a little thing.
With some help of the user "iecs" at the topic "Chart.js V2: Add prefix or suffix to tooltip label" I was able to change the label at the tooltip. It now shows nicely my desired prefix and suffix:
tooltips: {
enabled: true,
mode: 'single',
backgroundColor: 'rgba(0,0,0,0.9)',
titleFontSize: 14,
titleFontStyle: 'bold',
titleFontColor: "#FFF",
bodyFontSize: 12,
bodyFontStyle: 'normal',
bodyFontColor: "#FFF",
footerFontSize: 12,
footerFontStyle: 'normal',
footerFontColor: "#FFF",
cornerRadius: 5,
callbacks: {
label: function(tooltipItems, data) { // Solution found on https://stackoverflow.com/a/34855201/6660135
//Return value for label
return 'Usage: ' + tooltipItems.yLabel*1000 + ' watt';
}
}
}
When I try to add exactly the same code to modify the title I got undefined
at the place where a date and time should be displayed:
tooltips: {
enabled: true,
mode: 'single',
backgroundColor: 'rgba(0,0,0,0.9)',
titleFontSize: 14,
titleFontStyle: 'bold',
titleFontColor: "#FFF",
bodyFontSize: 12,
bodyFontStyle: 'normal',
bodyFontColor: "#FFF",
footerFontSize: 12,
footerFontStyle: 'normal',
footerFontColor: "#FFF",
cornerRadius: 5,
callbacks: {
title: function(tooltipItems, data) {
//Return value for title
return 'Date: ' + tooltipItems.xLabel + ' GMT+2';
},
label: function(tooltipItems, data) { // Solution found on https://stackoverflow.com/a/34855201/6660135
//Return value for label
return 'Usage: ' + tooltipItems.yLabel*1000 + ' watt';
}
}
With the answer of user "Lukman" at the topic "Print content of JavaScript object? [duplicate]" I discovered that I can display the content of the "tooltipItems object":
alert(tooltipItems.toSource())
This displayed an interesting difference regarding the "tooltipItems" object between the "title" and the "label".
The "tooltipItems" object at the "label" display this as content:
({xLabel:"2016-08-07 23:41:57", yLabel:0.261, index:70, datasetIndex:0})
While the "tooltipItems" object at the "title" displays this as content:
[{xLabel:"2016-08-07 23:41:57", yLabel:0.261, index:70, datasetIndex:0}]
The beginning characters and ending characters are different.
The one of "label" can be read with tooltipItems.yLabel
but the one of "title" can't be read with tooltipItems.xLabel
because it shows me "undefined". The whole title will now be Date: undefined GMT+2
insteas of Date: 2016-08-07 23:41:57 GMT+2
What did I mis? Can someone explain me the differences between the 2 outputs of the object contents of "tooltipItems" and how to read the "xLabel" and "yLabel" indexes?
I encountered a similar problem too, but was resolved with this.
return 'Date: ' + tooltipItems[0].xLabel + ' GMT+2';