0

I an updating a 10 year website that used highcharts and I am converting it to chartjs.

In the data it had a extra field for the tooltip that was a html string.

Example:

data: [
{x: 0,y:395.8,extra: 'Aug 11 2020 00:56:48<br/>12% <br>395.8  <br/>53.9 <br/>56.1 Inches, 95 \u00B0F<br/>4.674 , 0 , 582 , 1000 , 00'},
{x: 1,y:390.2,extra: 'Aug 11 2020 01:56:48<br/>12% <br>390.2  <br/>53.1 <br/>56.2 Inches, 93.2 \u00B0F<br/>4.681 , 0 , 582 , 1000 , 00'},
{x: 2,y:395.8,extra: 'Aug 11 2020 02:56:49<br/>12% <br>395.8  <br/>53.9 <br/>56.1 Inches, 93.2 \u00B0F<br/>4.676 , 0 , 582 , 1000 , 00'}
}]

I was wonder how to do the same with chart.js. The data is being put in from PHP database. So I can change it from the extra field, but where would I put it?

Thanks in advance. ( new to chart.js sorry)

1
  • You have used the Highcharts tag - please be aware that chart.js and Highcharts are two different, standalone libraries. Commented Aug 13, 2020 at 7:49

1 Answer 1

1

You can achieve what you want if you disable the default tooltip and create a custom one.

If you have access to the php API, I would personally change the data so that the date is on the x axis rather than just numbers.

var customTooltip = function(tooltip) {
  $(this._chart.canvas).css('cursor', 'pointer');

  var positionY = this._chart.canvas.offsetTop;
  var positionX = this._chart.canvas.offsetLeft;

  $('.chart-tooltip').css({
    opacity: 0
  });

  if (!tooltip || !tooltip.opacity) {
    return;
  }

  if (tooltip.dataPoints.length > 0) {
    tooltip.dataPoints.forEach(function(dataPoint) {
      var content = extra[dataPoint.index];

      $('#tooltip').html(content);
      $('#tooltip').css({
        opacity: 1,
        top: positionY + dataPoint.y + 'px',
        left: positionX + dataPoint.x + 'px',
      });
    });
  }
};

I have created a fiddle to demonstrate using your data: https://jsfiddle.net/y01ewbtz/

Sign up to request clarification or add additional context in comments.

7 Comments

When I copy all the code into page It shows the chart but the tooltip is not showing like it does with jsfiddle
Can you expand on "not showing like it does with jsfiddle" please? is this a css/style issue or is the tooltip not showing at all?
It works now. Added more data and one of the extra was eztra
The datapoint.datasetIndex is not increasing so the tooltip is always the first one.
Sorry about that, I'm not sure why the datasetIndex is not incrementing, anyway it can be replaced with index, please see the new fiddle
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.