A step-by-step guide to identifying the clicked bar on a Chart.js graph

When using Chart JS to create a line bar chart, I am looking to specifically identify which bar was clicked on the chart and determine the index of that bar. This will allow me to display specific details for each clicked bar on a table. For example, clicking on any bar for the year 2010 should give me index 0, and for the year 2011, it should give me index 1. However, I want the index to be based on the position of the clicked bar within the year. For instance, clicking on the second bar of the year 2010 should give me index 1.

https://i.sstatic.net/pe7ya.png

Here is the HTML:

<div id = "myTable" class="container-lg" style="margin-left: 300px;">
        <div class="table-responsive">
            <div class="table-wrapper">
                <table class="table table-bordered">
                    <thead>
                        <tr style="background-color: #4B4B4B">
                            <th style="font-weight: 500; color: white; text-align:center" colspan="2">Feedback from Thamama F</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td style="text-align:center">John Doe</td>
                            <td style="text-align:center">John Doe</td>
                        </tr>
                        <tr>
                            <td style="text-align:center">John Doe</td>
                            <td style="text-align:center">John Doe</td>
                        </tr>
                        <tr>
                            <td style="text-align:center">John Doe</td>
                            <td style="text-align:center">John Doe</td>
                        </tr>
                        <tr>
                            <td style="text-align:center">John Doe</td>
                            <td style="text-align:center">John Doe</td>
                        </tr>
                        <tr>
                            <td style="text-align:center">John Doe</td>
                            <td style="text-align:center">John Doe</td>
                        </tr>
                        <tr>
                            <td style="text-align:center">John Doe</td>
                            <td style="text-align:center">John Doe</td>
                        </tr>
                        <tr>
                            <td style="text-align:center">John Doe</td>
                            <td style="text-align:center">John Doe</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        function Show() {
            var x = document.getElementById("myTable");
            if (x.style.display === "none") {
                x.style.display = "block";
            } else {
                x.style.display = "none";
            }
        }
    </script>
    

Here is the JavaScript:

'use strict';

        // Code for chart color settings

    

Answer №1

After examining your feedback and understanding your issue, I have identified a potential solution for you.

options:{
   onClick: function (event, elements){  
       if (elements.length > 0) {   
           // Accessing the clicked element
           const clickedElement = this.getElementAtEvent(event);

           // Retrieving the group id of the clicked element
           const groupIndex = clickedElement[0]._index;

           // Obtaining the id of the clicked element within the group
           const barIndex = clickedElement[0]._datasetIndex;
       }
   }
}

By utilizing this code snippet, you will be able to determine the specific details of the clicked element, such as its group/column association and its unique identifier within the group (e.g. identifying which of the five bars was clicked).

Answer №2

Implement this code snippet within your chart configuration to easily load your HTML table data.

options:{
       onClick: handleChartClick
}

function handleChartClick(event, data){
   if(data.length === 0){
     //load the table here
   }
}

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

Having trouble with making a POST request in Node.js using Express.js and Body-parser?

Just starting out with nodejs and currently in the learning phase. I've encountered an issue where my POST request is not functioning as expected. I set up a basic html form to practice using both GET and POST requests. Surprisingly, the GET request w ...

How can I insert a button into a Flatlist using React Native?

Is there a way to add a single scrollable button inside a FlatList without duplicating it? I've been experiencing issues where adding a button inside the FlatList results in multiple buttons being displayed. On the other hand, placing the button outs ...

Directive in AngularJS fails to trigger upon form reset

I encountered an issue with a directive used within a form, specifically when clicking on a button with the type reset. The problem can be replicated on this stackblitz link. The directive I'm using is quite simple - it sets the input in an error stat ...

Checkbox selection causing Bootstrap accordion to collapse

Hey everyone, I'm currently working with Bootstrap 5 accordion and facing an issue where the input checkbox is triggering the "collapse" event of the accordion. I attempted to relocate the checkbox outside the scope of the accordion button but that so ...

Utilizing CSS to align all HTML form elements at the center

Is it possible to centrally align all form labels and input fields by using CSS? If so, what would be the approach for a form where the label text is displayed vertically above the input field? #fieldset label { display: block; } #fieldset input ...

Internet Explorer does not support the use of a:focus

Unfortunately, the issue with a:focus not working in IE is still unresolved. I have been searching for a solution, but have not been able to find one yet. <div class="city-selection"> <ul> ...

Achieve maximum height with background images

Having trouble with responsiveness on my box containing a background image. I am aiming for the box to adjust its height based on the background image, as I have set the background-size attribute to auto. html: <div class="index_boxs" id="discover_win ...

Unspecified data stored within an object

I am looking to populate a page with data from the server and have the ability to update the information. To achieve this, I am using formbuilder to fetch data from the server as the default value. Here's how I am implementing it: createForm(){ ...

Modifying the color of elements within a picture

I am in search of the perfect web technology or JavaScript library that can help me achieve a specific functionality. My aim is to change the colors of particular objects within an image. I am looking to create a tool where users can select a color, and th ...

Using a PhoneGap solution to establish communication with a remote database

Creating a phoneGap app that resembles Facebook, where users can post messages and receive comments from friends. The app is built on HTML, JS, and phoneGap and is connected to a MySQL database on a remote server. As a beginner, I am unsure how to pull and ...

Tips for choosing a table row that is not the first or last cell

#MyTable tr+tr:hover { background: #dfdfdf; } <table id="myTable"> <tr> <td>A</td> <td>B</td> <td>C</td> </tr> <tr> <td>1</td> <td>2</td> &l ...

The body-parser module in express 4.0 is currently not accessible for the route handler

I am attempting to send a PUT request via Google Postman in the following format: PUT /updateUser/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="debcbcbc9eadadadf0bdb1b3">[email protected]</a> HTTP/1.1 Host: loca ...

Tips for securely concealing an API key during website deployment on Netlify

Recently, I created a small website using Javascript just for fun and I'm looking to deploy it to Netlify. However, I've encountered an issue with the API key that the website uses. I'm struggling to figure out how to conceal this key. Curre ...

Leverage flex columns in Bootstrap 4.0 for advanced layout options

Hey, I need some assistance to set up columns in my code. Here's the current code snippet: <div class="container-fluid h-100"> <div class="row h-100"> <div class="flex-column h-100">side menu</div> <div ...

Comparing .innerHTML with createElement() | Exploring setAttribute() versus the Direct method*

Someone mentioned that this approach was not considered "proper", but I didn't pay much attention to it until I encountered a run-time error in IE9. Now, I need help converting the code to utilize object properties instead. What is the reason behind i ...

Tips for receiving a reply from S3 getObject in Node.js?

Currently, in my Node.js project, I am working on retrieving data from S3. Successfully using getSignedURL, here is the code snippet: aws.getSignedUrl('getObject', params, function(err, url){ console.log(url); }); The parameters used are: ...

Arranging Bootstrap dropdown and buttons on a single line

Check out my code snippet here: http://jsfiddle.net/52VtD/7462/ I'm facing an issue where I want to align my dropdown and buttons on the same line, but the dropdown being a div, it stays on the line below. How can I ensure they are on the same line? ...

Identifying a user's unique identity through a POST request using Node.js

Currently, I am developing a browser game that integrates voice communication. To capture audio within the browser, I have chosen to use wami-recorder. This tool relies on Flash technology to make a POST request to the server containing the recorded audio. ...

Using Ajax to send a variable to PHP and then selecting data from an SQL database

Currently, I am facing an issue where I need to pass a variable to my "fetch" PHP file. In the fetch.php file, I execute a query to a MySQL database with certain parameters. However, I have hit a roadblock in the process. I am able to retrieve the variab ...

Loop through two sets of data and perform multiplication on specific attributes when they match

I have a unique item that looks like this Object {SD00002:1,SD00011:3,SD00002:6} The values of the properties are set automatically. Currently, I have an array of similar objects as shown in the image below: https://i.sstatic.net/pSkvf.jpg My goal is to ...