What is the best way to determine the index of the area that was clicked on in chartjs?

I am currently working with a chart that may not have elements at specific indices, but I am interested in determining the index of the area clicked.

https://i.sstatic.net/rEMbG.jpg

When hovering over an area without an element, the assigned tooltip is displayed. I would like to achieve the same functionality with a click action and retrieve the index of the area.

Answer №1

If you are working with chart js options, make sure to utilize the onClick event feature. You can find more information about it here.

By using onClick, you will be able to access the event and refer to the code snippet below to retrieve the index accordingly.

In addition, the x and y values are also displayed for reference.

I believe the following code snippet should help resolve your concern:


var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["2015-01", "2015-02", "2015-03", "2015-04", "2015-05", "2015-06", "2015-07", "2015-08", "2015-09", "2015-10", "2015-11", "2015-12"],
    datasets: [{
      label: '# of Tomatoes',
      data: [12, 19, 3, 5, 2, 3, 20, 3, 5, 6, 2, 1],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        ...
        ],
      borderColor: [
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)', 
       ...
        ], 
      borderWidth: 1
    }]
  },
  options: {
    responsive: false,
    onClick: function(c,i){
     e = i[0];
    console.log("index",e._index)
    var x_value = this.data.labels[e._index]; 
    var y_value = this.data.datasets[0].data[e._index]; 
    console.log("x value",x_value); 
    console.log("y value",y_value); 
    }, 
    scales: {
      xAxes: [{
        ticks: { 
         maxRotation: 90, 
         minRotation: 80 
        } 
      }],
      yAxes: [{ 
       ticks: {  
        beginAtZero: true       
        }
      }]
    }
  }
}); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.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

Issue in Angular Material: The export 'MaterialComponents' could not be located in './material/material.module'

I'm relatively new to Angular and I am encountering some difficulties when trying to export a material module. The error message that appears is as follows: (Failed to compile.) ./src/app/app.module.ts 17:12-30 "export 'MaterialComponents&ap ...

What could be causing the error message 'Why is 'push' property undefined in React Native?

Within my index.ios.js file, I have the following: renderScene(route, navigator){ return <route.component navigator={navigator} {...route.passProps}/> } as well as render() { return ( <Navigator initialRoute={{name: &a ...

What is the best way to retrieve a specific item from an array of objects stored in JSON format using React?

I have received a json file named data.json which contains multiple objects in an array. My goal is to extract the value of a specific key from each object. To achieve this, I am utilizing react redux to fetch these values and present them in a table forma ...

Encountering an issue while attempting to fetch a value from a nested object property with VueJS Interpolation

I'm struggling to properly display nested arrays in Vue JS. Below is a snippet of my JSON data: { "id": 1, "slug": "test-page", "banner": { "title": "banner title", "subTitle": "my sub title", "hasSubTitle": false, "hasClass": " ...

Encountering issues while trying to install Java using NPM

Encountering errors when attempting to run the following command to install java dependencies for NPM. NPM install -g java In need of assistance to fix this error. C:\WINDOWS\system32>npm i -g java [email protected] install C:\D ...

What is the best way to handle requests once a SpookyJS script has finished running?

Occasionally, I find myself needing to log in and extract some data from a specific website. To automate this process, I developed a CasperJS script that runs on Heroku. My goal is to create an endpoint like the following: app.get('/test', func ...

Leveraging jest.unmock for testing the functionality of a Promise

I've implemented Auth0 for managing authentication in my React App. Below is the code snippet I am trying to test: login(username: string, password: string) { return new Promise((resolve, reject) => { this.auth0.client.login({ ...

Nodejs application encountering a problem with the findUser method in Active Directory

I have encountered an issue while using the activedirectory npm package with Nodejs v16.18.1. The code snippet below is used for authentication and finding user details: Could someone please assist with this? async authUserActiveDirectory(usernameAD: stri ...

Refreshing Slickgrid: Updating grid data with data fetched from an AJAX source

Within the app I am developing, there exists a data grid alongside select boxes that allow users to set filters. Upon selection of these filters, an AJAX call is made to retrieve a new array of data from the server. The challenge I currently face is wipin ...

The body onload function fails to run upon the page loading

I'm having trouble with my body onload function not executing. When I load the page, I want to display all records that are selected in the drop_1 dropdown and equal to ALL. I have a script that sends values q and p to getuser.php. The values sent are ...

Having trouble with the onClick function in React?

Here is my simple react code: Main.js: var ReactDom = require('react-dom'); var Main = React.createClass({ render: function(){ return( <div> <a onClick={alert("hello world")} >hello</a> </ ...

What is the best way to halt the ticking of this clock in JavaScript?

I can't seem to figure out how to stop this clock using JavaScript Even though I press the stop button, the clock keeps running <!DOCTYPE html> <html> <head> <h1> Welcome to the clock. Press the stop button to halt the clo ...

Execute the command "prisma migrate dev" to update the existing database

I'm currently in the process of configuring Prisma migrate on a pre-populated MySQL database in my development environment, but I'm facing challenges getting it to function correctly. 1. After executing prisma db pull successfully to generate th ...

Here are the steps to trigger a pop-up window in JavaScript that is filled with data fetched via an AJAX call:

I'm currently working on a java class where I need to insert a link into a table grid. This code is specific to the internal API of our company. /***MyCustomLink.java*********/ customLink.setOnClick( "fetchURL", return false;); addGridItem("cu ...

Shifting the MUI DataGrid Pagination table to the left with CustomPagination: A step-by-step guide

Hey everyone, I am currently diving into the MUI data grid to gain a better understanding. In order to meet my design requirements for a table view, I have incorporated the DataGrid component from MUI. For pagination, I am utilizing their custom implementa ...

CSS - owl carousel automatically stretches images to full width

Here is the code snippet that I am working with: $(document).ready(function() { $('.owl-carousel').owlCarousel({ loop:true, items:4, autoplay:true, autoplayTimeout:2000, autoplayHoverPause:true }); }); #owl-demo ...

HTML and JavaScript: Struggling to include multiple parameters in onclick event even after escaping quotes

I am struggling to correctly append an HTML div with multiple parameters in the onclick function. Despite using escaped quotes, the rendered HTML is not displaying as intended. Here is the original HTML code: $("#city-list").append("<div class='u ...

When making a variable call outside of a subscriber function, the returned value is 'undefined'

I find myself in a situation where I have to assign a value to a variable inside a subscriber function in Angular. The issue is that the variable returns 'undefined' when called outside of the Subscribe function. Here's what I'm encount ...

What are the steps to integrating an HTML source with jQuery Autocomplete?

Struggling with a challenging ajax call to an HTML source that is essential. The goal is to convert the html response into a format suitable for displaying in the jQuery autocomplete list. Working with Autocomplete and Ajax $("#From, #To, #FromVacation ...

Ways to calculate the product of two numbers using AngularJS within an HTML document

I am currently experimenting with AngularJS to create a unit conversion tool. I have set up two dropdown menus with unit values and would like to calculate the product of the selected values from the dropdowns. I have created a jsfiddle with my code, and I ...