Hiding tooltips for specific datasets in Chart.js version 2.8

I'm working with a graph that has four datasets. Two of them show the count of values, while the other two represent a goal or target for each value. I want to group all tooltips together when hovering over the graph, but exclude the tooltips for the goal lines. How can this be achieved?

The code below includes some sample data and the tooltip displays all labels.

var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["January", "February", "March", "April", "May", "June"],
    datasets: [{
        label: 'Count type 1',
        data: [48, 33, 32, 35, 42, 38],
        backgroundColor: 'transparent',
        borderColor: 'rgba(255, 204, 0, 1)',
        fillColor: 'rgba(255, 204, 0, 0.1)',
        pointBorderColor: 'transparent',
        pointBackgroundColor: 'rgba(255, 204, 0, 1)',
        pointRadius: 4,
        borderWidth: 2,
        lineTension: 0.3
      },
      {
        label: 'Goal 1',
        data: [48.000, 47.040, 46.080, 45.120, 44.160, 43.200],
        backgroundColor: 'transparent',
        borderColor: 'rgba(0, 255, 0, 1)',
        fillColor: 'transparent',
        pointBorderColor: 'transparent',
        pointRadius: 0,
        borderWidth: 0.4,
        lineTension: 0
      },
      {
        label: 'Count type 2',
        data: [24, 37, 30, 22, 29, 18],
        backgroundColor: 'transparent',
        borderColor: 'rgba(255, 0, 0, 1)',
        fillColor: 'rgba(255, 0, 0, 0.1)',
        pointBorderColor: 'transparent',
        pointBackgroundColor: 'rgba(255, 0, 0, 1)',
        pointRadius: 4,
        borderWidth: 2,
        lineTension: 0.3
      },
      {
        label: 'Goal 2',
        data: [24.000, 23.520, 23.040, 22.560, 22.080, 21.600],
        backgroundColor: 'transparent',
        borderColor: 'rgba(0, 255, 0, 1)',
        pointBorderColor: 'transparent',
        pointRadius: 0,
        borderWidth: 0.4,
        lineTension: 0
      }
    ]
  },
  options: {
    tooltips: {
      enabled: true,
      mode: 'index',
      intersect: false,
    }
  }

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<canvas id="myChart"></canvas>

I have experimented with different approaches, but have not been able to achieve the desired result without issues like flickering tooltips or only excluding one dataset.

Answer №1

During my exploration of the issue, I came across a solution using the filter function. This approach was inspired by a helpful response to a similar problem.

filter: function (tooltipItems, data) {
    var label = data.datasets[tooltipItems.datasetIndex].label;
    if ((label == "Goal 1")||(label == "Goal 2")) {
        return false;
    } else {
        return true;
    }
}

Below is the code snippet from my original query that incorporates this filter logic.

var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["January", "February", "March", "April", "May", "June"],
    datasets: [{
        label: 'Count type 1',
        data: [48, 33, 32, 35, 42, 38],
        backgroundColor: 'transparent',
        borderColor: 'rgba(255, 204, 0, 1)',
        fillColor: 'rgba(255, 204, 0, 0.1)',
        pointBorderColor: 'transparent',
        pointBackgroundColor: 'rgba(255, 204, 0, 1)',
        pointRadius: 4,
        borderWidth: 2,
        lineTension: 0.3
      },
      {
        label: 'Goal 1',
        data: [48.000, 47.040, 46.080, 45.120, 44.160, 43.200],
        backgroundColor: 'transparent',
        borderColor: 'rgba(0, 255, 0, 1)',
        fillColor: 'transparent',
        pointBorderColor: 'transparent',
        pointRadius: 0,
        borderWidth: 0.4,
        lineTension: 0
      },
      {
        label: 'Count type 2',
        data: [24, 37, 30, 22, 29, 18],
        backgroundColor: 'transparent',
        borderColor: 'rgba(255, 0, 0, 1)',
        fillColor: 'rgba(255, 0, 0, 0.1)',
        pointBorderColor: 'transparent',
        pointBackgroundColor: 'rgba(255, 0, 0, 1)',
        pointRadius: 4,
        borderWidth: 2,
        lineTension: 0.3
      },
      {
        label: 'Goal 2',
        data: [24.000, 23.520, 23.040, 22.560, 22.080, 21.600],
        backgroundColor: 'transparent',
        borderColor: 'rgba(0, 255, 0, 1)',
        pointBorderColor: 'transparent',
        pointRadius: 0,
        borderWidth: 0.4,
        lineTension: 0
      }
    ]
  },
  options: {
    tooltips: {
      enabled: true,
      mode: 'index',
      intersect: false,
      filter: function(tooltipItems, data) {
        var label = data.datasets[tooltipItems.datasetIndex].label;
        if ((label == "Goal 1") || (label == "Goal 2")) {
          return false;
        } else {
          return true;
        }
      }
    }
  }

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<canvas id="myChart"></canvas>

Answer №2

After much searching, I finally found the perfect plugin that fits exactly what I was looking for: https://github.com/chartjs/chartjs-plugin-annotation

var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["January", "February", "March", "April", "May", "June"],
    datasets: [{
        label: 'Count type 1',
        data: [48, 33, 32, 35, 42, 38],
        backgroundColor: 'transparent',
        borderColor: 'rgba(255, 204, 0, 1)',
        fillColor: 'rgba(255, 204, 0, 0.1)',
        pointBorderColor: 'transparent',
        pointBackgroundColor: 'rgba(255, 204, 0, 1)',
        pointRadius: 4,
        borderWidth: 2,
        lineTension: 0.3
      },
      
      {
        label: 'Count type 2',
        data: [24, 37, 30, 22, 29, 18],
        backgroundColor: 'transparent',
        borderColor: 'rgba(255, 0, 0, 1)',
        fillColor: 'rgba(255, 0, 0, 0.1)',
        pointBorderColor: 'transparent',
        pointBackgroundColor: 'rgba(255, 0, 0, 1)',
        pointRadius: 4,
        borderWidth: 2,
        lineTension: 0.3
      }
    ]
  },
options: {
responsive: true,
tooltips: {
    enabled: true,
      mode: 'index',
      intersect: false, 
    },
    
    annotation: {
        annotations: [{   
            type: 'line',  
            mode: 'horizontal',
            drawTime: 'afterDatasetsDraw',
            id: 'a-line-1',
            scaleID: 'y-axis-0',
            value: 48,
            endValue: 43,
            borderColor: 'rgb(75, 192, 192)',
            borderWidth: 2,
            label: {
                backgroundColor: 'rgba(255,204,0, 0.4)',
                fontColor: 'rgba(0, 0, 0, 0.6 )',
                fontSize: 12,
                enabled: true,
                content: 'Goal from 48 to 43',
                yAdjust: -18,
                xAdjust: 0,
            }
        },
        {
            type: 'line',   
            mode: 'horizontal',
            drawTime: 'afterDatasetsDraw',
            id: 'a-line-2',
            scaleID: 'y-axis-0',
            value: 24,
            endValue: 21,
            borderColor: 'rgb(75, 192, 192)',
            borderWidth: 2,
            label: {
                backgroundColor: 'rgba(255,0,0,0.4)',
                fontColor: 'rgba(255, 255, 255 )',
                fontSize: 12,
                enabled: true,
                content: 'Goal from 24 to 21',
                yAdjust: 14,
                xAdjust: 0,
            }
        }]
    },
    
    scales: {
        yAxes: [{
            scaleLabel: {
                display: true,
                labelString: 'interface'
            },
            ticks: {
                beginAtZero: true
            }
        }]
    }
}

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<script src="https://rawgit.com/chartjs/chartjs-plugin-annotation/master/chartjs-plugin-annotation.js"></script>

<canvas id="myChart"></canvas>

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

Maintaining the position of an image during animation movements

I am experiencing an issue with a grid of images where, upon clicking one image, all the other images move down. However, the remaining image is pulled to the top left corner. I suspect this is happening because by removing the other images, the remaining ...

Ways to enable users to input grammatical equations while verifying certain rules in a text box

I am looking for validation of equations in HTML, not evaluation. I want to allow users to input equations like the following in a textbox, with validation: 400 - IF(age > 32, 6, 4) + 10 The 'age' is a fixed string, and there will be other ...

Unusual occurrences regarding scope in the world of JavaScript and d3.js

Currently, I am working on a project using a mix of react.js and d3.js. While coding, I encountered a strange behavior that I can't quite figure out. componentWillMount() { this.setState({ dummyData: [{ price: 13, ...

"Connecting a checkbox and radio button to a button for page navigation using JavaScript - a step-by-step guide

How can I link a checkbox and a radio button with a button to open a page using JavaScript? For instance: Select a checkbox and a radio button, then click a button to open a page. This concept caters to everyone: Select a checkbox and a radio button, then ...

Load Vue 3 components dynamically using a string-based approach

Exploring ways to dynamically load components based on a string input. Here is an attempt at achieving this: <component v-for="component in components" :is="eval(component)" /> However, this approach does not yield the desired r ...

Incorporating jsbi into a TypeScript project while adhering to strict mode

I have been developing a TypeScript library that relies on native BigInts. While it functions perfectly in Chrome, I encountered some issues with Safari. After some research, I stumbled upon the jsbi "polyfill" that seems to solve this problem. Unfortunat ...

The ajax form submit function does not have the capability to automatically post content

On this particular webpage, there is a visible form labeled form A which contains a submit button with a post action. <form name="payFormCcard" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> I am looking to cre ...

The HTML element received focus from either a mouse click or keyboard input

Is there a way to determine if an HTML element (such as a select tag) has received focus via mouse-click, keyboard input, or a JavaScript function? <select onfocus="foo(event)"></select> <script> function foo(e) { if (e.??? == &apos ...

Issue with processing secure 3D payments on live mode in Stripe

I am currently implementing 3D secure payment on a website. It works perfectly in the test environment with test cards, but when I switch to live keys, it does not generate a pop-up for user confirmation. Instead, it completes the payment without any confi ...

Using ThreeJS in an iframe on a mobile device can lead to crashes in the browser due to multiple

I am encountering an issue with my ThreeJS based pages that are included via Iframe into other pages. The problem arises when switching between the two pages with ThreeJS Iframe on a mobile phone (specifically an iPhone 7 with just 1GB RAM). After two or ...

Having trouble making jQuery code disable input field based on checkbox status

Is there a way to automatically disable the price input field once the checkbox is checked and clear any existing text? I seem to be having trouble with my current code.. <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <scr ...

Ways to control the number of boxes that are checked

I am currently working on a script to restrict the number of checkboxes that can be checked, but I am encountering an issue where the script is disabling all checkboxes on the page. Is there a way to only disable a specific checkbox within a certain div? ...

Return a response from the controller method without using the express response object

When attempting to handle the scenario where a fetch for an item does not return anything from another method that lacks the express response, I encounter an issue. I invoke this method from another one that has the express response: const updateItem = asy ...

ForEach function does not work following a shallow copy

I'm encountering an issue where forEach is not recognized as a function. Can someone assist me with this problem? Essentially, I need to generate a shallow copy of filteredSettlements and use it for looping through the items. Below is a snippet of the ...

Tips for disabling scrolling on touch screens for input elements

I am facing an issue with a modal that is positioned on top of a scrollable document body. I am trying to prevent the scrolling of the document when I swipe my finger on the modal. $(document).on('touchstart touchmove', function(e){ e.preventDef ...

AngularJS causing a modal popup to appear even when the associated button is disabled

When using a Bootstrap modal popup form that opens on button click in AngularJS, I noticed that the modal still appears even when the button is disabled. Can someone help me understand why this happens? Here is the code for the button: <a class="btn b ...

Ways to reuse test cases across different test suites in Protractor

There are some shared test cases that can be utilized across different test suites. For example, suppose suite x and suite y both require the same set of test cases to function properly. To address this, a separate .js file containing the shared code has ...

"Exploring the Art of Showcasing Duplicate Image Count from User Input in an

I need to showcase multiple duplicates of 2 different images on a webpage. Users are asked for the duplication speed, which I have already implemented, and also how many copies of each image they want. function show_image() { var img = document.create ...

Exploring the attrTween function in Angular with D3 insights

I'm currently trying to grasp the concept of utilizing the function attrTween in D3. My goal is to create a pie-chart using the example found at http://bl.ocks.org/mbostock/5100636. However, I've encountered some challenges when it comes to the ...

Converting an HTTP request and incorporating a success function in Typescript and Angular2

I am working on a http request: private getValues() { this._watchlistElements.map(v => this.http.get('http://localhost/getValue/' + v.xid) .subscribe(res => { this._values.push(res.json()); })); }; When the request ...