Mixter
Mixter

Reputation: 193

Clickable chart data points to open new pages

I would like to be able to click on the bars and directly open a new page associated with that bar.

I have researched and was able to make the x-axis clickable, but I need the bars or circle clickable instead.

var chart = c3.generate({
  bindto: '#chart',
  data: {
    columns: [
      ['data1', 30, 200, 100, 400, 150, 250],
      ['data2', 50, 20, 10, 40, 15, 25]
    ],
    type: 'bar'
  },
  axis: {
    rotated: true
  }
});

var arrayOfLinks = [
  "http://google.com",
  "http://google.com",
  "http://google.com",
  "http://google.com",
  "http://google.com",
  "http://google.com",
];

d3.selectAll('.c3-axis-x .tick tspan')
  .each(function(d, i) {
    // augment tick contents with link
    var self = d3.select(this);
    var text = self.text();
    self.html("<A xlink:href='" + arrayOfLinks[i] + "'>" + text + "</A>");
  });
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.7.11/c3.min.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.7.11/c3.min.js"></script>
<div id="chart"></div>

I am almost certain that the fix lies in this line of code:

d3.selectAll('.c3-axis-x .tick tspan')

What should the argument be? 'data.coloums[1]','bar' ?

Please shed some light.

Upvotes: 0

Views: 531

Answers (1)

Coola
Coola

Reputation: 3142

As pointed out here in the issue, for bar charts you can specify an onclick function, when you pass in the data. This function can trigger an even to window.open the link.

A snippet of the code is here:

var chart = c3.generate({
  bindto: '#chart',
  data: {
    columns: [
      ['data1', 30, 200, 100, 400, 150, 250],
      ['data2', 50, 20, 10, 40, 15, 25]
    ],
    type: 'bar',
    //define the onclick function
    onclick: function (d) { 
      console.log(d) //checks the data
      //note that the index for the values gets passed as d.x
      window.open(arrayOfLinks[d.x]); 
    },
  },
  axis: {
    rotated: true
  },

});

A full working block for the code is here:

http://bl.ocks.org/akulmehta/87f4903a4686deb8285381b8e816ce4d

Upvotes: 2

Related Questions