Distinguishing the clicked stack in a grouped stacked bar chart (using Chart.js) - deciphering the mystery

I have implemented a bar chart similar to the image shown. The chart consists of two stacks grouped together, each stack containing multiple datasets. This implementation involves the use of Vue.js and vue-chartjs.

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

For handling click events on the chart, I am utilizing the onClick option provided by Chart.js. The e parameter represents the event object, and i contains an array of datasets used in the chart. By accessing the index of a dataset, we can determine which group was clicked. However, identifying which specific stack within the group was clicked remains a requirement.

onClick: (e, i ) => {
  console.log(i[0]._index)
}

The data utilized for generating the chart includes:

this.datacollection = {
  labels: [...Object.keys(total)],
  datasets: [
    {
      label: 'Started',
      stack: 'Stack 0',
      backgroundColor: 'rgb(112,108,236,0.2)',
      borderColor: 'rgb(112,108,236,0.3)',
      borderWidth: 5,
      data: Object.values(active)
    },
    {
      label: 'Assigned (all)',
      stack: 'Stack 0',
      backgroundColor: 'rgb(137,37,252 , 0.2)',
      borderColor: 'rgb(137,37,252 , 0.2)',
      borderWidth: 5,
      data: Object.values(total),
    },
    // Additional dataset configurations...
  ]
}

Chart options include:

{
  responsive: true,
  maintainAspectRatio: false,
  scales: {
    xAxes: [
      {
        stacked: true
      }
    ],
    yAxes: [
      {
        ticks: {
          beginAtZero: true
        },
        stacked: false
      }
    ]
  },
  onClick: (e, i) => { console.log(i[0]._index) }
}

If you require further details or wish to view the complete code sample, refer to the specified files:

test.vue:
<template>
  <div>
    <bar-chart :chart-data="datacollection" :options="options"></bar-chart>
  </div>
</template>

// Code block for test.vue...

BarChart.js:

import { Bar , mixins } from 'vue-chartjs'
const { reactiveProp } = mixins

export default {
  extends: Bar,
  mixins: [reactiveProp],
  props: ['chartData' , 'options'],
  mounted () {
    if (this.chartdata)
      this.renderChart(this.chartdata)
  }
}

Answer №1

I discovered a solution using the method chart.getElementAtEvent(evt)

let chart = this.$refs.barChart.$data._chart;

                let datasetIndex = chart.getElementAtEvent(evt)[0]._datasetIndex

                let stack = chart.getDatasetMeta(datasetIndex).stack;

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 Angular Material md-input-container consumes a significant amount of space

Currently, I am exploring a sample in Angular Material. It appears that the md-input-container tag is taking up a substantial amount of space by default. The output is shown below: https://i.sstatic.net/hQgpT.png However, I have come across the md-input- ...

What is the scope of values in Javascript/jQuery?

Similar Query: Does JavaScript have a range() equivalent? Can we define a range in JavaScript or jQuery similar to how it's done in Python? For example: x = range(1,10) x = [1,2,3,4,5,6,7,8,9] Appreciate your inputs. ...

What is the best way to implement forwardRef in a distinct select component?

Currently, I am utilizing react, typescript, and styled-components to work on my project. Specifically, I am aiming to create a select component for use in React Hook Form. Initially, everything seemed to be in order, but I encountered an error from typesc ...

Enhancing User Experience with Jquery Dialog and Implementing Stylish Text Presentation

My goal is to design a customer support dialogue that includes a title and two lines of text. The first line should display an error message, while the second line will feature a bold customer service number. To provide further clarity, I have created a vi ...

Encountered a connection error while attempting to establish a connection in Node.js

Every time I try to execute the code, I encounter this error message: throw new Error('Most middleware (like ' + name + ') is no longer bundled with express and must be installed separately ^ Error: Most middleware(like BodyParser) is ...

Is there a way to exclude specific routes in AngularJS ui router?

In my current web application, I am utilizing the ui-router to manage routing. Within one of my views, there is a canvas that interacts with a third-party library which dynamically loads images through HTTP GET requests. However, due to ui.router's $u ...

Issue with Angular translation when utilizing a dynamic key variable

I am currently developing a project with Angular Js and incorporating the Angular-translate module In a specific scenario, I encountered an issue where the translation key needed to be stored as a variable. To address this, I created an object within the ...

Please send the element that is specifically activated by the onClick function

This is the HTML code I am working with: <li class="custom-bottom-list"> <a onClick="upvote(this)"><i class="fa fa-thumbs-o-up"></i><span>upvote</span></a> </li> Here is my JavaScript function for Upvot ...

Safari and iOS users may not experience the onended() event triggering

Code snippet performs as expected on Chrome 80.0 and Firefox 74.0 (OSX 10.14.6). However, when testing on OSX Safari 13.0.5 or iOS (using Chrome, Safari), the <div> element fails to turn blue, suggesting that the onended callback is not triggering. C ...

Why are my Bootstrap nav-tabs not showing tab-content in MVC?

I'm dynamically creating tab navigation from controllers using a list. <div class=""row> <div class="col-xl-3"> <!-- Tabs nav --> <div class="nav flex-column nav-pills nav-pills-custom" id="v-p ...

Ways to incorporate customizable text and images into three.js

Recently, I've been experimenting with adding new images and text as textures to a 3D object using fabric js for my 3D configurator. My codebase is inspired by this GitHub repository, and I'm also utilizing this code from CodePen. One key aspect ...

Developing instance members and methods in JavaScript

After encountering a challenge with creating "private" instance variables in JavaScript, I stumbled upon this discussion. Prior to posing my question, I wanted to provide a thorough overview of the problem. My goal is to showcase a complete example of corr ...

Iterate through the complex array of nested objects and modify the values according to specified conditions

I am currently iterating through an array of objects and then delving into a deeply nested array of objects to search for a specific ID. Once the ID is found, I need to update the status to a particular value and return the entire updated array. Issue: Th ...

Utilize useMediaQuery for identifying various breakpoints in your design

Currently, I am working on detecting multiple breakpoints in my application to ensure dynamic column generation on a Grid. Although I have managed to accomplish this task, the code appears somewhat repetitive. Is there a method through which I can simpli ...

Loading module retrieves data from database when required

My goal is to create a module that fetches categories from a database once and then allows me to query it by categoryName in order to retrieve the model. For example, using categoryResolver('sweaters'). I am utilizing objection.js for this purpos ...

Is it possible that the fetch request and expressJS server are not compatible even though they are both functioning properly?

Within a server component of a NextJS app, I have a fetch request that is causing some unexpected behavior. Here is a simplified version of the code: export async function bookRoom(params: BookingRequest) { const {rooms, startTime, endTime} = params; ...

Unlock the power of Google Maps with the dynamic capabilities of

Looking to integrate jQuery with Google Maps? Attempting to mirror this example, here's the code I'm currently using. However, the map isn't displaying on my webpage - it's just blank. Any thoughts on what could be causing this issue? ...

Encrypting data between two Node.js servers

I am looking to create a Node.js daemon that can operate across multiple computers while facilitating message exchange between the daemons. Security is paramount, so I want to ensure the communication is encrypted. However, I am uncertain about which encry ...

Oops! Looks like there was an error: weight is not defined when trying to calculate BMI with the HTMLButtonElement

I'm currently working on a project to create a BMI calculator following specific instructions. I've managed to follow all the guidelines except one regarding the letsCalculateBMI function. The instruction states: letsCalculateBMI should extrac ...

"Trouble with making jQuery AJAX calls on Internet Explorer versions 8 and 9

I've been searching for the answer to this problem without any luck. I have a page with jquery ajax calls to an API service. It works well in Chrome, Safari, Firefox, and IE 10, but fails in IE 9 and 8. Here is the code: $.ajax({ ...