Having issues with Angular chart.js onClick event? Learn how to retrieve all elements of a bar when it is clicked on

As a newcomer to Chart.js, I am exploring how to implement click events for when a chart is generated.

My current challenge involves accessing all the elements of a bar upon clicking it. Unfortunately, the onClick method is not functioning as expected at the moment. Despite the chart rendering correctly, I am unable to interact with it as intended. Any assistance in resolving this issue would be greatly appreciated.

controller($state, $scope, $rootScope) {
    $scope.myChart;

....

    $scope.go = function myFunc() {
      document.getElementById("chartContainer").innerHTML = ' ';
      document.getElementById("chartContainer").innerHTML = '<canvas style="margin-top: 10px; padding-top: 20px; height:90% ; background-color: ' + vm.options.backgroundColor + '; " id="myChart" click="onClick"></canvas>';
    var ctx = document.getElementById("myChart").getContext('2d');

       render($scope.myChart, ctx, vm.options.barColor, vm.options.backgroundColor, labelVal, value);
  };
  $scope.onClick = function (evt) {
    console.log("Testing"); 
  };

}
var render = function createChart(myChart, ctx, barColor, backgroundColor, labels, values) {


myChart = new Chart(ctx, {
    type: 'bar',

    data: {
        labels: labels,
        datasets: [{
            backgroundColor: barColor,

            data: values,
                }]

    },
    options: {
        events: ['click'],
        chartArea: {
            backgroundColor: backgroundColor,
        },
        global: {
            responsive: true,
            maintainAspectRatio: false,
        },
        scaleBeginAtZero: true,
        maintainAspectRatio: false,

        scales: {
            xAxes: [{
                ticks: {
                    autoSkip: false,
                }
                }],
            yAxes: [{
                ticks: {
                    beginAtZero: true,
                    min: 0
                }
                    }]
        }
    }
});

}

Answer №1

CONSIDER implementing the given on-click function within your chart settings ...

options: {
   onClick: function(e) {
      var selected = this.getElementAtEvent(e);
      if (selected.length) {
         console.log(selected[0])
      }
   },
   ...
}

Based on my understanding, this method should be effective

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

Retain the chosen choice even when the updated options list no longer includes that value

I am using a select element with ngOptions that is based on an array. The contents of this array may change dynamically. However, when the new array value does not include the selected option value, the selectController sets the option value to undefined. ...

Tips for implementing AngularJS on a webpage transfer

I am a beginner in learning AngularJS. I have gone through the basic tips on W3Schools, but now I am stuck on implementing the login function. When I click the "sign in" button, the webpage should redirect to the login page of the website. However, I am ...

Design a div in the shape of a trapezium with clipped overflow

Is there a way to create a trapezium using CSS/Html/Canvas? I have attempted to do so, but my current method is messy and not practical. div { width:0; margin-left:-1000px; height:100px; border-right:1000px solid lightblue; border-top:60px solid tra ...

Making a jQuery AJAX request for JSON from a separate domain

My goal is to send an AJAX request to , expecting JSON data in return (not sure if JSONP) However, when I click on the button to make the AJAX request, I encounter this issue: http://prntscr.com/8xswr1 (Google Chrome Console) Upon double-clicking ' ...

A guide on integrating array map with a v-for loop in Vue

Struggling to understand how to implement a loop within another loop in Vue? This task might seem simple with React, but Vue presents its own challenges when it comes to using loops with arrays in templates/JSX. The input data follows a specific format fr ...

When I use my loop to generate Google Map markers, the positioning is not accurate and the markers do not appear on the map. However, manually inputting the positions

There seems to be an issue with displaying Google map markers based on objects in the markers array after looping through it. I noticed that when creating a second component and setting the position manually, the marker appears correctly. However, upon ins ...

Exploring the nativeElement property of a customized Angular HTML element

In my Angular Jasmine Unit Test, I am testing a third-party slider component in my application using the following code snippet: Here is the HTML: <ui-switch id="EditSwitch" name="EditSwitch" (change)="togglePageState()"></ui-switch> And her ...

Trouble with $http response not appearing in AngularJS application

Currently, I am in the process of developing an angularjs application and encountering a challenging issue with setting up the $http connection to a php file. The header is displaying a response that I echoed from php. Nevertheless, two key problems persis ...

Utilizing AngularJS to incorporate a global scope function within another function

I have a specific AngularJS function named editlocation that triggers a Modal window to edit three data points. Following this process, I aim to execute plotmarkers, which is utilized in another scenario of an ng-click. Despite attempting different approa ...

Encountering a Jasmine undefined error while utilizing Jasmine jQuery

Currently, I am working in the Yeoman Angular environment and utilizing Jasmine for testing purposes. In my index.html file, I have included both Jasmine and Jasmine jQuery like so: <script src="bower_components/jasmine/lib/jasmine-core/jasmine.js"> ...

The onClick event is not functioning properly with React's select and option elements

Looking for a way to get the option value from each region? const region = ['Africa','America','Asia','Europe','Oceania']; <div className="options"> <select> ...

Stagnant variable value after onClick event

After exploring various solutions, none seem to quite fit my needs. I want to update the variable "currentIndex" when a user clicks on an image. Currently, the change occurs within the onClick function but does not affect the outside variable. I am unsur ...

Error encountered in Chrome while trying to fetch Next.js PWA with the use of next-pwa: Unhandled TypeError

Hello, I was recently working on a Next.js project and attempted to convert it into a PWA using next-pwa. To start off, I created the next.config.js file. const withPWA = require('next- pwa'); module.exports = withPWA({ pwa: { dest: ...

What is the best way to create a point within a mesh?

I have several meshes and I'd like to insert a point randomly within the confines of hexagon[0]. How can this be achieved? var Hexagon=new Array(); Hexagon[0] = new THREE.Mesh( HexagonExtrude[0],material[0] ); Hexagon[1] = new THREE.Mesh( HexagonExtr ...

Establishing global date restrictions for the DatePicker component in Angular 8 using TypeScript across the entire application

I am currently learning Angular 8 and I am looking to globally set the minimum and maximum dates for a datepicker in my application. I would like to accomplish this by using format-datepicker.ts. Any suggestions on how I can achieve this? Min date: Jan 1, ...

Renovating code structure in JavaScript

As I develop a small application that interacts with a database, I have opted to use Promises instead of the callback pattern for simplicity in my code. Through my coding experience, I've noticed a recurring pattern in my logic and I'm seeking ad ...

Unable to invoke the jQuery function within CakePHP3

I am having trouble calling the jQuery function mentioned below in my CakePHP3 MVC project. There are no error messages, but nothing seems to be happening. The code is set up so that jQuery gets included automatically. The function I am trying to call sh ...

The Vue.js application is experiencing issues with the v-for functionality

I am working on a Vue.js application where I am fetching a list using ajax: $.ajax({ method: 'POST', dataType: 'json', url: this.base_info.url + 'getavailability?token=' + this.token, data: this.search_inf ...

Transitioning React Hover Navbar Design

I'm currently revamping a click-to-open navbar into a hover bar for a new project. I have successfully implemented the onMouseEnter and onMouseLeave functions, allowing the navbar to open and close on mouse hover. However, I am facing an issue with ad ...

Looking to Identify a Click Within a Complicated Component and Retrieve the Component's ID

Currently, I am working with React for development and have a need to capture clicks at the topmost parent level for performance reasons. const clickHandler = (e) => { console.log("clickHandler", e.target) --> I want to identify the child ...