How can I modify the color in vue-google-chart when a filter option is selected?

I created a stack column chart with a filter that changes the color to blue when selected.

Here is my Vue app:

https://codesandbox.io/s/vue-dashboard-chart-6lvx4?file=/src/components/Dashboard.vue

I expected the selected color to match the color in the stack column.

Could someone please advise on how to achieve this using Vue-google-charts?

Thank you and best regards, Dede

Answer №1

If you're looking for a solution that meets your requirements, check out this codesandbox example. Start by assigning colors to each series in the chartOptions:

series: {
          0: { color: "#3366cc" },
          1: { color: "#dc3912" },
          2: { color: "#ff9900" },
          3: { color: "#109618" },
          4: { color: "#990099" },
          5: { color: "#0099c6" },
          6: { color: "#333" },
},

Moreover, create another object to hold default colors under the data property:

defaultColors: {
        0: { color: "#3366cc" },
        1: { color: "#dc3912" },
        2: { color: "#ff9900" },
        3: { color: "#109618" },
        4: { color: "#990099" },
        5: { color: "#0099c6" },
        6: { color: "#333" },
},

Then, when filtering data, update the color of the first series like so:

this.chartOptions.series[0].color = this.defaultColors[idx].color;

Answer №2

Check out the latest update to Nima Ebrazeh's answer (fixed a minor bug and added graph title):

Vue.component("gchart", VueGoogleCharts.GChart);
new Vue({  
  el: "#demo",
  data() {
    return {
      chartData: [
        [
          "Month",
          "New",
          "Verified",
          "Regitered ID",
          "On Playing",
          "Finished",
          "Active",
          "Inactive",
        ],
        ["January", 7, 4, 18, 15, 9, 10, 0],
        ["February", 16, 22, 23, 30, 16, 9, 8],
        ["March", 10, 2, 20, 13, 14, 21, 18],
      ],
      chartOptions: {
        chart: {
          title: "Player Performance",
        },
        legend: { position: "bottom", maxLines: 5 },
        bar: { groupWidth: "75%" },
        isStacked: true,
        title: "Player Performance (please chose category to filter)",
        series: {
          0: { color: "#3366cc" },
          1: { color: "#dc3912" },
          2: { color: "#ff9900" },
          3: { color: "#109618" },
          4: { color: "#990099" },
          5: { color: "#0099c6" },
          6: { color: "#333" },
        },
      },
      chartEvents: {
        click: (e) => {
          let idx = e.targetID.match(/\d+/g);
          if (idx && idx.length < 3) {
            idx = Number(idx[0])
            this.isFiltered ? this.allData() : this.filterChart(idx);
          }
        },
      },
      newData: [],
      isFiltered: false,
      defaultColors: {
        0: { color: "#3366cc" },
        1: { color: "#dc3912" },
        2: { color: "#ff9900" },
        3: { color: "#109618" },
        4: { color: "#990099" },
        5: { color: "#0099c6" },
        6: { color: "#333" },
      },
    };
  },
  methods: {
    filterChart(idx) {
      this.allData();
      for (let i = 0; i < this.newData.length; i++) {
        this.newData[i] = [this.newData[i][0], this.newData[i][idx + 1]];
      }
      this.chartOptions.series[0].color = this.defaultColors[idx].color;
      this.isFiltered = true;
    },
    allData() {
      this.newData = [...this.chartData];
      this.chartOptions.series[0].color = this.defaultColors[0].color;
      this.isFiltered = false;
    },
  },
  mounted() {
    this.allData();
  },
})

Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fd8b8898d09a92929a9198d09e959c8f898ebdcdd3ced3cf">[email protected]</a>/dist/vue-google-charts.browser.js"></script>
<div id="demo">
  <div id="app">
    <GChart type="ColumnChart" :data="newData" :options="chartOptions" :events="chartEvents" />
  </div>
</div>

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

Testing in Jasmine: Verifying if ngModelChange triggers the function or not

While running unit tests for my Angular app, I encountered an issue with spying on a function that is called upon ngModelChange. I am testing the logic inside this function but my test fails to spy on whether it has been called or not! component.spec.js ...

Methods to maintain the select2 dropdown event open while interacting with another select2 dropdown

I have a situation where I need to dynamically add a class to a div whenever a select2 dropdown is open. To achieve this functionality, I am utilizing the open and close events of select2. The current code successfully adds the class when opening a selec ...

Tips for modifying JSON property names during the parsing process

As outlined in the JSON.parse documentation, a reviver function can be utilized to modify the value of each property within the JSON data. Here is an example: JSON.parse('{"FirstNum": 1, "SecondNum": 2, "ThirdNum": 3}', function(k, v) { return ...

How to Set Checkbox Values in VueJS with true or false Status

I have a query regarding a checkbox feature on my website built with VueJS. I am trying to achieve the following functionality: if the checkbox named special is checked, then store the value 1 in the database column. How can I implement this correctly? Th ...

What is the best way to locate and send a message to a particular channel within a server?

I've been working on a Discord bot using Discord.js and I'm currently attempting to create a welcome command. My goal is to send a message to a specific channel within my server. However, due to recent updates in discord.js, I'm having troub ...

Employing ngModel within an (click) event in Angular 4

I have this html code snippet: <div class="workflow-row"> <input type="checkbox" id="new-workflow" [(ngModel)]="new_checkbox"> <label>New Workflow</label> <input type="text" *ngIf="new_checkbox" placeholder="Enter ...

What could be causing my update function to not run when I refresh the page?

As a non-developer trying to learn react.js, I am working on a section of my website that needs to update every few seconds with new content like a photo, header, and body text. I've encountered an issue where the data refreshes correctly after the p ...

How to Prevent Scrolling When Modal is in Use on Full Page JS

I am trying to achieve the functionality where when the modal is open, I want to prevent full-page scrolling in JavaScript. The issue arises when I open the modal and try to scroll, it ends up moving the content that's behind the modal, which is actua ...

I have created an Express.js application. Whenever I visit a page, I consistently need to refresh in order for the variables to appear correctly

Hello, I'm seeking some assistance. Despite my efforts in searching for a solution, I have not been successful in finding one. I've developed an application using Express.js that includes a basic form in jade. The intention is to display "Yes" i ...

a reliable approach to gain entry to properties that do not exist

Utilizing Google Apps Script along with JavaScript code, I am leveraging UrlFetchApp to retrieve data from the Stripe API in order to fetch an invoice. Subsequently, the Script processes the retrieved data and updates a Google Sheet template with it. An i ...

Obtaining status codes from URLs can be achieved by leveraging various methods

Hey there, I'm just starting out with javascript and AngularJS. Here's a function I wrote to retrieve JSON data from the server: function getProducts() { return $http.get(urlProducts).then( //Success function(resp ...

Issue with Angular drag and drop functionality arises when attempting to drop elements within an n-ary tree structure displayed using a recursive template

I am currently exploring the functionality of angular material drag and drop. Within my application, I have implemented an n-ary tree structure. Since the specific form of the tree is unknown beforehand, I have resorted to using a recursive template in or ...

Adding data from a database into an object in PHP for temporary use during the loading process can be achieved by following

I'm a beginner in PHP and I have some code that retrieves category type data from a database. I want to temporarily store this data in a PHP object while the page is loading. Initially, I need to load all predefined data and then use it when a certain ...

What is the best way to create a distinct key for the key prop in my map function within a React component?

This is the initial code I have: class Board extends Component { static defaultProps = { nrows: 5, ncols: 5, chanceLightStartsOn: 0.25 }; constructor(props) { super(props); this.state = { hasWon: false, board: this. ...

Executing Python script via AJAX or jQuery

I need to execute Python scripts from JavaScript. The goal is to provide an input String to the Python script as an argument and then showcase the output on our webpage. Below is the Python code that runs smoothly on my Linux box: ./sample.py 12345 produc ...

VueJS: Prevent users from selecting options in the list that have already been chosen

Currently, I am delving into Vue.js and experimenting with creating a simple list that matches country codes to tax rates in various countries. Although it may seem mundane, I believe this exercise will prove useful in my future projects. This is the sele ...

Leveraging icons with Bootstrap 4.5

I am currently exploring how to incorporate Bootstrap 4.5 icons using CSS. Do you have any examples of code that could guide me on how to achieve this? I am specifically interested in understanding the required CSS declarations that would allow me to use t ...

When the VueJS element is rendered on Chrome addon, it suddenly vanishes

I have been using a developer mode addon successfully in Chrome for quite some time. Now, I want to add a button to my Vue-powered page. Here's the code snippet: let isletCtl = document.createElement('div') isletCtl.id ...

JavaScript method of retrieving an object inside an array nested within another object via multer

Below is my custom multer function to handle file uploads - const storage = multer.diskStorage({ destination: (req, file, callback) => { let type = req.params.type; let path = `./data/${type}`; fs.mkdirsSync(path); callback(null, path) ...

Adjust a Specific CSV Value Using JavaScript and NodeJS

Hey there, I have a CSV file that I need to extract and modify a specific value from. Let's take this as an example: CSV 90,90,90,90,90 3,1,1000,2,931 I'm looking to access the number "2" in this CSV. How would I go about doing that? And once ...