Utilizing various colors for tooltipFontColor in Chart.js

I'm trying to customize the font color for tooltip labels in Chart.js, but I want to set different colors based on certain conditions. Specifically, I want the label color to be white by default, but change to red if a condition is met. I've looked into using the customTooltips option, but I'm open to any solution.

Here's an example of what I'm hoping to achieve:

if (difference[i] >= 0) { 
    tooltipFontColor: "#FFF" 
} else {
    tooltipFontColor: "#F00" 
}

The challenge is that the difference array contains both positive and negative values. I need Chart.js to dynamically adjust the colors based on these values.

Any insights or assistance would be greatly appreciated. Thank you!

Answer №1

Changing Tooltip Colors Based on Data Value


Preview


Custom Script

Implementing a feature to change tooltip colors based on data values using Chart.js library.
See the code snippet below for details:

new Chart(ctx).Line(data, {
    // Overriding default tooltip behavior
    tooltipEvents: [],
    onAnimationComplete: function () {
        // Modifying chart.js binding with custom adjustments
        Chart.helpers.bindEvents(this, ["mousemove", "touchstart", "touchmove"], function (evt) {
            var activePoints = (evt.type !== 'mouseout') ? this.getPointsAtEvent(evt) : [];
            this.eachPoints(function (point) {
                point.restore(['fillColor', 'strokeColor']);
            });
            Chart.helpers.each(activePoints, function (activePoint) {
                activePoint.fillColor = activePoint.highlightFill;
                activePoint.strokeColor = activePoint.highlightStroke;
            });
            
            if (activePoints.length !== 0) {
                if (activePoints[0].value >= 0)
                    this.options.tooltipFontColor = "#FFF";
                else
                    this.options.tooltipFontColor = "#F00";
            }
            this.showTooltip(activePoints);
        });
    }
});

Fiddle - http://jsfiddle.net/xyz789ab/

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

Using jQuery to Validate Input Text Control Depending on Radio Selection

How can I ensure that the input text linked to the selected radio option is filled in? For instance, in the example above: If Contact 1's Email radio option is chosen, the Email text field for Contact 1 must not be empty, while the Phone and US Mai ...

Toggle visibility of div content when hovering over a link by leveraging the data attribute, with the div initially visible

I have a collection of links: <p><a href="#" class="floorplan initial" data-id="king"><strong>King</strong></a><br> 4 Bedrooms x 2.5 Bathrooms</p> <p><a href="#" class="floorplan" data-id="wood">< ...

React Error: Unable to iterate over this.state.descriptions

Currently facing an issue while trying to resolve this error https://i.stack.imgur.com/BZ304.png The goal is to generate an automated form using the following function: let descriptionsForm = ( <form> {this.state.descriptions.map((d ...

Ways to prompt a specific text value to generate varied responses

Whenever I try to input the letter "h", I expect a specific value in return but for some reason, it's not working as intended. Despite my best efforts to troubleshoot the issue, I have been unsuccessful in finding a solution. It's frustrating bec ...

Using the same bone structure to share skeletons among SkinnedMeshes in Three.JS

I've been grappling with the challenge of incorporating and removing clothing pieces to an existing skeleton (Clothing meshes and body meshes should share skeleton) but I always seem to encounter strange results. All the clothing items that I intend ...

UV mapping with Plane BufferGeometry in Three.js

I'm facing some challenges creating a buffergeometry plane, specifically with the uv coordinates. Despite following advice from Correct UV mapping Three.js, I can't seem to achieve the desired result. Below is the snippet of code for the uv coor ...

Retrieve the content of the 'div' element, but exclude certain text

I have a task to copy the content from a div into a textarea, allow for editing within the textarea, and ensure that any changes made are saved back to the original div. I also need to filter out an attribute, such as data-bind: "some stuff;", set for the ...

What is the method used by Bootstrap to create a darker page background behind a modal?

I am struggling to understand how Bootstrap darkens the background of a page when a modal is displayed. Even though a class is added to the body tag (modal-open), the effect on the background isn't clear to me. Learn more about Bootstrap modals here ...

Locating items within a complex array and identifying their corresponding positions

I recently found an interesting code snippet from a different question that allowed me to identify an object. However, I am now faced with the challenge of determining the position of that object within the array. Let's take a look at the example belo ...

transferring data from a form with a binary image file to store in an SQL server

I am aiming to create a form where users can upload an image along with some data fields. Currently, I can only get either the image or the data fields to work separately. The following code allows me to upload an image to my SQL database as binary data. I ...

Mongoose Alert: Unable to Create Schema Instance

Below is the Schema file that I'm using: const mongoose = require("mongoose"); const ProblemSchema = new mongoose.Schema( { slug: { type: String, required: true, unique: true, }, title: { type: String, ...

Ways to display form choices that are influenced by other form selections

In my form, the user is supposed to choose a specific item at the end. As they fill in the initial options, the subsequent fields below change dynamically. Here is an example: Type: { t1:{ Number of X:{ 1:{...} 2:{...} ...

Cypress - Adjusting preset does not impact viewportHeight or Width measurements

Today is my first day using cypress and I encountered a scenario where I need to test the display of a simple element on mobile, tablet, or desktop. I tried changing the viewport with a method that seems to work, but unfortunately, the config doesn't ...

Testing the number of times module functions are called using Jest

As someone who is relatively new to JavaScript and Jest, I am faced with a particular challenge in my testing. jest.mock('./db' , ()=>{ saveProduct: (product)=>{ //someLogic return }, updateProduct: (product)=>{ ...

Determine if a specific value is present within an array consisting of multiple objects using Mongoose

In my collection, I have a scenario where I need to utilize the $in operator. Person = { name: String, members: [ {id: String, email: String}... {}] } Currently, I am using the following: Person.find({members: {"$in": [id1]}}) However, I am aware of ...

JavaScript file encountering a problem with its global variables

What is causing the alert("2") to pop up first instead of it being second? Why am I encountering difficulty creating global variables c and ctx? Is there a way for me to successfully create these two global variables in order to utilize ...

Exploring and accessing elements and nested objects within a dynamically named element in JavaScript using JSON syntax

Receiving a JSON response from an API, here's what the data looks like: [{ "order_id":"1111", "restaurant_id":"ABC", "fullfillment":"Delivery", "order_channel":" ...

Having trouble getting the Google motion chart to work with asynchronous JSON requests

I have been using the code below to make a request for a JSON file and then parsing it. google.load('visualization', '1', {packages: ['controls', "motionchart", "table"]}); google.setOnLoadCallback(function(){ createTable($(& ...

Guide on displaying ajax data using PHP

I'm attempting to display the user-entered data by using AJAX to transfer it and then trying to print or echo it with PHP, but I'm having trouble getting it to work. enter code here Here is my code: <html> <head> <title> ...

Executing a Javascript function when a form is submitted

function validateForm() { alert("Form submitted successfully"); return true; } <form onsubmit="return validateForm()" action="add.php" method="post" id="p1"> <center>Add New Survey</center> <p>&nbsp;&l ...