Click on a bar in ChartJS to alter its background hue

Utilizing chartjs to create a basic bar chart here. I've made the bars clickable, and when a user clicks on one, I want to change its background color to show that it's selected.

Can this be done?

Thanks!

Edit: Example added below. https://jsfiddle.net/10n39cLz/1/ Extracting the clicked element using: this.getElementAtEvent(e)

Answer №1

I stumbled upon a rather graceful solution by simply adjusting the backgroundColor stored within an array. Unfortunately, a simple render() wasn't sufficient, so I had to resort to using update()..

It would have been nice to utilize ES6 in this scenario :-)

var colorArray = ['rgb(124, 181, 236)',
    'rgb(124, 181, 236)',
    'rgb(124, 181, 236)',
    'rgb(124, 181, 236)',
    'rgb(124, 181, 236)',
    'rgb(124, 181, 236)'];

var chart = new Chart(document.getElementById("trendChart"), {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: colorArray
    }]      
  },
  options:{
    onClick: function(e){
    var element = this.getElementAtEvent(e);
            for(var i=0;i<colorArray.length;i++){
        colorArray[i] = 'rgb(124, 181, 236)';
    }
         colorArray[element[0]._index] = 'red';
      this.update()
    },
           scales: {
        yAxes: [{
            ticks: {
            fontColor:'#fff'
           }
        }],
                    xAxes: [{
            ticks: {
            fontColor:'#fff'
          }
         }],                    
     },
   legend:{
      display:false
    }
  }
})

Answer №2

When you take some time exploring the console and your specific element, you will notice that by logging your element, you are presented with an array containing only one object (which is the element in question).

This particular object contains various children, including _index (as utilized in your code snippet).
This is where you can begin customizing the background of your element.

If you navigate deeper into the child element known as _chart, you will eventually be able to modify the specific bar you desire.

I have made changes to your code snippet to showcase the outcome: here is the updated result.


Keep in mind that the modification will no longer be visible if you mouseleave from the element.

Answer №3

To achieve the desired outcome, a slight adjustment to the active property is all that's needed.

new Chart(document.getElementById("trendChart"), {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: 'rgb(124, 181, 236)'
    }]      
  },
  options:{
    onClick: function(e){
    var element = this.getElementAtEvent(e);

    // Adjusting the color of the active object
    this.active[0]._chart.config.data.datasets[0].backgroundColor = "red";

    if(element.length > 0){
            alert("Clicked on a bar with index: "+element[0]._index+". Now this bar should be marked as active.");
      }
    },
           scales: {
        yAxes: [{
            ticks: {
            fontColor:'#fff'
           }
        }],
                    xAxes: [{
            ticks: {
            fontColor:'#fff'
          }
         }],                    
     },
   legend:{
      display:false
    }
  }
});

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

Retrieve the current global time accurately, utilizing an API to access internet-based time data within a React js framework

Seeking a way to retrieve current international time in React Js using internet const date = new Date(); The above code snippet retrieves the current device time, but I need an alternative solution. The issue is that when I change my device's time se ...

Using node.js to set the billing address while confirming a Stripe Payment intent

Is there a way to specify the billing address of a payment intent with Node.js? When using the Stripe.js browser-side framework, I can easily accomplish this by utilizing Stripe elements and the stripe.confirmPayment function, which automatically captures ...

What is the best way to switch between search results shown in an li using AngularJS?

Looking for a way to toggle a list that appears when a user searches in my app. I want the search results to hide when the search bar is closed. How can I achieve this? I think Angular might be the solution, but I'm stuck on how to implement it. I tri ...

Tips for centering a bootstrap card on the screen using reactjs

I've been struggling to keep my card centered on the screen despite using align-items and justify-content. I've researched on various websites to find a solution. //Login.js import React, { Component } from 'react'; import './App ...

Removing data with sweetalert in a Ruby on Rails application

Hey there, I'm currently exploring the use of sweet alert js to enhance the appearance of my alert boxes. In my table, I have a specific data deletion feature that is triggered by a standard JavaScript alert confirmation. However, when attempting to i ...

Sending Data from Dialog Box1 to Dialog Box2 in ASP.NET Using JavaScript

Is there a way to successfully transfer a value from Modal1 to Modal2? I am facing an issue where Modal1 opens Modal2 to receive a necessary value, but I keep encountering the error message: "Uncaught TypeError: Cannot read property 'click' of nu ...

Unable to initialize metro server due to the error "attachToServer is not a valid function"

After following the instructions in the original documentation, I executed npx react-native init AwesomeProject without making any changes. However, when I try to run npx react-native start or yarn start, I encounter an error stating that attachToServer i ...

What is the best approach to streamline and optimize this JavaScript logic code for greater efficiency?

Working on a project, I find myself dealing with 21 buttons that can be in either an active or inactive state. The state of certain buttons is influenced by the press of other buttons as well as their own activation. To handle this in my HTML, I utilize ng ...

Dynamic PHP content manipulated with jQuery Add/Remove functionality

I am new to jQuery and currently working on implementing a feature for my PHP page. I want to have an Add/Remove button/icon that, when clicked, will show a new set of fields (specifically Drop Down menus). The example I found only shows how to add a text ...

Is there a performance boost when using queue() and filter() together in jQuery?

I'm currently refactoring some Jquery code and I've heard that chaining can improve performance. Question: Does this also apply to chains involving queue() and filter()? For instance, here is the un-chained version: var self = this, co = ...

Achieving optimal performance with scoped CSS in Vue.js

As I work on creating a new app using VueJs, I have noticed the implementation of "css scoped" as shown below: <style scoped> .example { color: red; } </style> <template> <div class="example">hi</div> </template> ...

Change the output of Object.fromEntries

I've been working on updating the values of an object using the .fromEntries() method. The issue I am facing is that even though I am returning a modified Array of hours, when the function completes it reverts back to the original complete Array. If ...

Could the act of one function updating state and another immediately accessing it lead to a potential race condition occurring?

I am faced with a scenario where I have two components - one for uploading files and the other for submitting a form. Each component has its own callback function that needs to trigger a backend request once completed. My objective is to ensure that the ba ...

Unlock the full potential of integrating external APIs with Next.js

As a newcomer to NextJs, I am facing the task of making calls to an external Python API from my frontend. Upon discovering NextJs's integrated API feature through creating folders in the app directory, namely api/resource/route, I am wondering what th ...

The problem stemming from the implementation of the useNavigate() Hook in a personalized React-Admin application

I've encountered a complex issue in my React-Admin application. Whenever I attempt to utilize the useNavigate() hook within my custom login component (MyLoginPage), an error message pops up: [Route] is not a <Route> component. All component chi ...

Ways to display a specific element by its id while concealing others

I have a collection of items in a list, each with unique ids: <ul> <li id="item1">Item 1</li> <li id="item2">Item 2</li> <li id="item3">Item 3</li> </ul> <div class="item1">This is Item 1.</div> ...

Tips for implementing resizable Material-UI Dialogs

I'm working on a project that involves creating a dialog box that can be resized and dragged. While I found steps in the Material-UI Dialog documentation on how to make it draggable, I'm still looking for information on how to make it resizable. ...

Whenever I try to submit multiple forms that include file uploads using ajax in Laravel, an empty error message is displayed

Having trouble uploading files while using Ajax to submit multiple forms in Laravel. Data is being sent without any issues, but the file upload is resulting in an error stating the file is empty. I have been trying to solve this for the past two days and h ...

I would greatly appreciate any recommendations on how to troubleshoot and

I've been working on the "Map the Debris" challenge at freecodecamp, and I'm facing an issue. While my code works fine in my PC's editor, it doesn't satisfy the conditions when I paste it into the website area. Any suggestions on how t ...

Executing a JavaScript function in ASP.NET after a button click has been completed

Here is an ASP.NET button: <asp:Button ID="okButton" runat="server" Text="Okay" OnClick="okButton_Click" /> This is the okButton_Click function: protected void okButton_Click(object sender, EventArgs e){ //perform tasks here } There is also a Ja ...