Tutorial on Chartist.js and custom tooltips.
Tags: javascript, tailwindcss, programming, graphs
Published: 2021-11-10 16:44:47

The Chartist JavaScript library provides a high-level API to draw charts in various ways. It makes it easy to create the most common types of charts, and with its simple configuration options, you can get beautiful results quickly. In this tutorial, we’ll create a chart from scratch, step by step. You can also take a look at the [codesandbox example](https://codesandbox.io/s/custom-tooltip-with-chartist-js-41mk4) for this tutorial to see the final result. This tutorial assumes that you have some basic knowledge of HTML and JavaScript but no prior experience with Chartist.js.

##Setup
To get Chartist working with your project, you’ll need to import the Chartist.js files.
```html
<link rel="stylesheet" href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">
<script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
```
Make sure to add these between the `<head></head>` tag. The charts will render as SVG, which means they scale infinitely and can be printed or animated for use in infographics or presentations.

Next, you'll need to add the following snippet of code in the body of your html.

```html
<div class="ct-chart"></div>
```
And finally, you'll need the javascript.
```javascript
var data = {
  // A labels array that can contain any sort of values
  labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
  // Our series array that contains series objects or in this case series data arrays
  series: [
    [5, 2, 4, 2, 0]
  ]
};

// Create a new line chart object where as first parameter we pass in a selector
// that is resolving to our chart container element. The Second parameter
// is the actual data object.
new Chartist.Line('.ct-chart', data);
```
This is the bare minimum of what you need to start working with Chartist, pretty simple, right.

I was recently working on a project where I needed a tooltip to display every-time I hovered over a point, and it needed to display the series data. Chartist has a tooltip plugin, but I found this plugin to have a lot of issues and it didn't work well for me, so I decided to implement my own tooltip. Let's discuss customizing our chart and then I will cover how to create and customize a tooltip.

##Customizing Chartist
Here is what we're going to build. A stats card that displays a chart of daily user signups.
![Chartist daily users chart](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w378qbvkf4x4mvceokej.png)

To build this, I'm using [Tailwindcss](https://tailwindcss.com) for styling, you can build your own classes and use those, but I love Tailwind so I'm using it.

The HTML:
```html
<div class="relative w-1/3 mx-auto mt-20 h-40 bg-white rounded-md overflow-hidden overflow-y-scroll shadow">
  <div class="p-6 w-full">Daily Users</div>
  <div class="absolute w-full ct-chart">
    // This part is important! We will cover this when we customize the tooltip.
    <div class="hidden absolute inline-block chartist-tooltip bg-white text-xs shadow text-center px-3 py-1 rounded-md w-28">
       <span class="chartist-tooltip-meta"></span><br />
       <span class="chartist-tooltip-value"></span>
    </div>
  </div>
</div>
```

Our series or chart data:
```javascript
var data = {
  series: [
    [
      { meta: "2021-01-01", value: 0 },
      { meta: "2021-01-02", value: 5 },
    ]
  ]
};

// The meta and value will display in the tooltip.
// The value is what's used to create the line on the chart.
```
Next, are the chart options:
```javascript
var options = {
  // extends the chart the full width of the div
  fullWidth: true,

  // removes any padding
  chartPadding: 0,

  // options for the x axis
  axisX: {
    // the chart was display outside the card.
    // to fix that we move it up with the offset.
    offset: 64,

    // turns off the grid
    showGrid: false,

    // turns off the labels
    showLabel: false
  },
  // options for the y axis
  axisY: {
    // no offset was needed so we set it to 0
    offset: 0,

    // turns off the grid
    showGrid: false,

    // turns off the labels
    showLabel: false
  }
};
```
Handeling the tooltip:
```javascript
new Chartist.Line(".ct-chart", data, options).on("draw", function (data) {
    // We only want the tooltip to apply to the point.
    if (data.type === "point") {
      // What want the tooltip to display on mouseenter so we listen for that event.
      data.element._node.addEventListener("mouseenter", (e) => {
            
        // I'm getting the tooltip by its class name.
        const tooltip = document.getElementsByClassName("chartist-tooltip");

        // This is how we're setting the position of the tooltip.
        // This will set the top of the tool tip.
        tooltip[0].style.top = data.y - 50 + "px";

        // This will set the left of the tooltip. What this does is if you're on the
        // right side of the card the tooltip display left of the cursor, if you're on
        // the left side of the card the tooltip displays right of the cursor.
        tooltip[0].style.left =
          data.x > 200 ? data.x - 100 + "px" : data.x + "px";

        // Here we're removing the hidden class so that the tooltip will display.
        tooltip[0].classList.remove("hidden");

        // This gets the tooltip meta div.
        const meta = document.getElementsByClassName(
          "chartist-tooltip-meta"
        );

        // This sets the data for the meta information on the tooltip
        meta[0].innerHTML = data.meta;

        // This gets the tooltip value div.
        const value = document.getElementsByClassName(
          "chartist-tooltip-value"
        );

        // This sets the data for the value.
        value[0].innerHTML =
          data.value.y === 1
          ? data.value.y + " view"
          : data.value.y + " views";
    });

    // here we're listening for when the mouse leaves, and when it does
    // we add the class hidden to hide the tooltip.
    data.element._node.addEventListener("mouseleave", (e) => {
        const tooltip = document.getElementsByClassName("chartist-tooltip");
        tooltip[0].classList.add("hidden");
    });
  }
});
```

##Conclusion and Summary
Chartist.js is a javascript library that makes it simple to create beautiful charts using HTML5 canvas, without requiring any knowledge of how JavaScript works under-the-hood. With Chartist, you can get away with only knowing basic HTML and CSS syntax, while your data automatically turns into professional looking charts! While Chartists doesn’t have any pre-made chart types built in, you can always customize one to fit your needs by combining multiple elements in unique ways.