What is the best way to customize the hover-over label appearance for a time series in ChartJS?

In my Angular 8 setup, I am working with the 'Date' data type and configuring multiple datasets of a 'Cartesian' type. I have been referring to documentation from here for guidance. Despite setting up the X Axis using callbacks in my code, I am struggling to figure out how to customize the hover label differently. The chart seems to break if I deviate from the time format requirement.

    const dashInput = this.getDashboardInput();
    const daysDifference = (+dashInput.endDate.getTime() - +dashInput.startDate.getTime()) / 1000 / 60 / 60 / 24;

    if (daysDifference >= 150 ) {
      this.enrollmentsAndCompletionsChartInUI.options.scales.xAxes[0].time.unit = 'month';
      this.enrollmentsAndCompletionsChartInUI.options.scales.xAxes[0].time.displayFormats.month = 'MM/YY';
    } else if (daysDifference >= 60) {
      this.enrollmentsAndCompletionsChartInUI.options.scales.xAxes[0].time.unit = 'week';
      this.enrollmentsAndCompletionsChartInUI.options.scales.xAxes[0].time.displayFormats.week = 'MM/DD/YY';
    } else {
      this.enrollmentsAndCompletionsChartInUI.options.scales.xAxes[0].time.unit = 'day';
      this.enrollmentsAndCompletionsChartInUI.options.scales.xAxes[0].time.displayFormats.day = 'MM/DD/YY';
    }

I am seeking assistance on how to set the hover box property as it's not explicitly mentioned in the documentation. Any insights would be greatly appreciated as I might have overlooked a simple detail while reading through the guidelines.

The current configuration settings for ChartJs scales are overridden by the component according to the adjustments above.

scales: {
      xAxes: [{
        id: 'time axis',
        type: 'time',
        time: { 
          unit: 'day', 
          displayFormats: {
            day: 'MM/DD/YY'
          }
        }
      }],
      yAxes: [{
        scaleLabel: {
          display: true,
          labelString: 'Enrollments'
        },
        ticks: {
          beginAtZero: true,
          min: 0
        }
      }]
    }

https://i.sstatic.net/Xvpsl.png

To clarify, I aim to configure the hover-over behavior to mirror the formatting of the XAxis, such as '08/05/19.'

Answer №1

After some research, I stumbled upon this strategy:

Utilizing External (Custom) Tooltips By employing custom tooltips, you gain the ability to intervene in the tooltip rendering process, allowing for a personalized rendering approach. Typically, this is utilized to generate an HTML tooltip rather than one on canvas. The activation of custom tooltips can be done in either the global or chart configuration as shown below:

var myPieChart = new Chart(ctx, { type: 'pie', data: data, options: { tooltips: { // Disable the on-canvas tooltip enabled: false,

        custom: function(tooltipModel) {
            // Tooltip Element
            var tooltipEl = document.getElementById('chartjs-tooltip');

            // Creating element upon initial render
            if (!tooltipEl) {
                tooltipEl = document.createElement('div');
                tooltipEl.id = 'chartjs-tooltip';
                tooltipEl.innerHTML = '<table></table>';
                document.body.appendChild(tooltipEl);
            }

            // Conceal if no tooltip
            if (tooltipModel.opacity === 0) {
                tooltipEl.style.opacity = 0;
                return;
            }

            // Set caret Position
            tooltipEl.classList.remove('above', 'below', 'no-transform');
            if (tooltipModel.yAlign) {
                tooltipEl.classList.add(tooltipModel.yAlign);
            } else {
                tooltipEl.classList.add('no-transform');
            }

            function getBody(bodyItem) {
                return bodyItem.lines;
            }

            // Setting Text
            if (tooltipModel.body) {...}

});

For additional details, check out:

https://www.chartjs.org/docs/latest/configuration/tooltip.html#tooltip-configuration

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 ng-model is not properly syncing values bidirectionally within a modal window

I am dealing with some html <body ng-controller="AppCtrl"> <ion-side-menus> <ion-side-menu-content> <ion-nav-bar class="nav-title-slide-ios7 bar-positive"> <ion-nav-back-button class="button-icon ion-arrow-le ...

Using Javascript to display a Div element for a short period of time when the mouse is clicked

Having some trouble creating a hidden colored block that appears after a mouse press anywhere on the page, stays visible for 2 seconds, and then disappears until another mouse press triggers it again. I've tried using '.click(function' and o ...

Generating a new display div element using an anchor link

I've set up a div container with a button that, upon clicking, adds a class to an element in my markup causing it to expand and take over the entire screen. Markup before: <section class="isi" data-trigger="toggle" data-trigger-class="isi--show-i ...

A guide on verifying a username and password via URL using JavaScript

As I work on developing a hybrid application using the Intel XDK tool and jQuery Mobile framework for the user interface, one of my current tasks is implementing a login function. This function involves simply inputting a username and password and clicking ...

inserting a for-loop inside a div tag

I've created a script that modifies the background color and plays a sound in response to user input. The changes are triggered by the length of the input provided. Additionally, I have a div element where I aim to display the specific letter causing ...

Clear the applied style from a specific DIV element

Currently, I am working on iPhone development and have set up a webview with a DIV element. Within this DIV, I have added 'touchstart', 'touchend', and 'touchmove' events. However, I have noticed that after adding these event ...

Is it possible to declare two global variables with the same name in Angular?

There are two global variables that come from different third-party files with the same name. Previously, I would use them like this: declare var someVar; But now, how can I use both of these variables? declare var someVar; declare var someVar; Is th ...

What are some ways to enhance Rxjs syntax?

save(): void { combineLatest(this.selectedSorting$, this.selectedFilters$) .pipe( map((data) => { let obj = {}; if (data[0]) { obj['fil ...

Accessing the parent div in an Ajax success function

I am looking for a solution to hide a parent div when a link is clicked and an ajax call is successfully made. I have tried placing the hide() function within the success part of the ajax call, but it seems to not work: $('.mylink').click(functi ...

Design Your Own Custom Spherical Section Using Three.js

Currently, I am working on a project involving a sphere in THREE.js that I like to refer to as the master sphere. In this project, I have enabled the user to pinpoint multiple spots on the sphere which serve as markers for the corners of a polygon. These p ...

Guide to incorporating dynamic components into Angular Router

I am currently working on developing a pluggable Angular application. During my research, I came across the following insightful article: Building an extensible Dynamic Pluggable Enterprise Application with Angular Everything was going smoothly until I ...

Tips for disabling scrolling on a <div> using another <div> as a lock

I am facing an issue with a page where a div is appended to the body of an HTML. The problem is that there are two scrolls appearing - one on the new overlaying div and another behind it. Here is an approximate structure of the page, how can I ensure that ...

Tips for utilizing Angular Js to redirect a webpage

Can someone help me figure out how to redirect to another page using Angular Js? I've searched through various questions here but haven't found a successful answer. This is the code I'm currently working with: var app = angular.module(&ap ...

Is there a way to automatically refresh the template whenever a scope variable is changed?

My goal is to have the showOrder.html template rendered when the value of orderHistory.type (a scope variable initialized as 'list') changes to 'show'. This change occurs when a link is clicked in the orderHistoryList.html. The model is ...

How to conceal a Card component using v-if in Vue.js?

Does anyone know how to hide the Card when the third element of the select box is selected? I am a new developer and would appreciate any help with this issue. Sorry for my lack of experience. <b-form-select v-model="InputRatingPlate.RatingP ...

Organizing an HTML layout

Looking for a way to sort a div structure based on a parameter, I came across a small JavaScript that seems to not work as expected. It appears that the sorting function is not parsing the values perfectly... This is the logic I am using for sorting: < ...

Having trouble importing a TypeScript file from the node_modules directory in Angular 2

Incorporating Google Map places into my Angular 2 project has been a challenge. npm install angular2-google-map-auto-complete https://i.sstatic.net/Vwi5h.png An error is occurring as the module cannot be found: https://i.sstatic.net/jVonb.png Could so ...

I am searching for a Nodejs library that has the ability to serialize and deserialize paths composed of named components, such as URL pathnames. Can

Here is an example: formatPath("/:item1/:item2/:item3", {item1: "apple", item2: "banana", item3: "cherry"}) => /apple/banana/cherry deserializePath("/:item1/:item2/:item3", "/apple/banana/cherry") => {item1: "apple", item2: "banana", item3: "cher ...

Retrieve the parent object from the policy field type

Imagine you have a query that retrieves a list of products like the one below. query ProductList() { products() { name price stockQuantity isAvailable @client # This field exists only locally } } In addition, you've set up a type ...

What is the best way to forward specific props from a parent to its children?

Currently, I am working on a React + Typescript architecture called "forward." The purpose of this architecture is to pass all props received down to its children components. However, I have encountered an issue where I want to restrict the type of props ...