Search code examples
d3.jsdc.jscrossfilter

d3 onclick to get the specific path/bar reference


if I have a d3/dc chart, and I set a click event handler like so:

    var data = [{
    "city": "New York",
        "neighborhood": "N/A",
        "hits": 200
}, {
    "city": "New York",
        "neighborhood": "Brooklyn",
        "hits": 225
}, {
    "city": "New York",
        "neighborhood": "Queens",
        "hits": 1
}, {
    "city": "San Francisco",
        "neighborhood": "Chinatown",
        "hits": 268
}, {
    "city": "San Francisco",
        "neighborhood": "Downtown",
        "hits": 22
}, {
    "city": "Seattle",
        "neighborhood": "N/A",
        "hits": 2
}, {
    "city": "Seattle",
        "neighborhood": "Freemont",
        "hits": 25
}];
var pieChart = dc.pieChart("#pieChart"),
    rowChart = dc.rowChart("#rowChart");
var ndx = crossfilter(data),
    cityDimension = ndx.dimension(function (d) {
        return d.city;
    }),
    cityGroup = cityDimension.group().reduceSum(function (d) {
        return d.hits;
    }),
    neighborhoodDimension = ndx.dimension(function (d) {
        return d.neighborhood;
    }),
    neighborhoodGroup = neighborhoodDimension.group().reduceSum(function (d) {
        return d.hits;
    });

pieChart.width(200)
    .height(200)
    .slicesCap(4)
    .dimension(cityDimension)
    .group(cityGroup);
pieChart.filter = function() {};

    var colorScale = d3.scale.ordinal()
            .domain(["San Francisco", "New York", "Seattle"])
            .range(["#D82C8C", "#17A7CF", "#E58304"]);

    pieChart.colors(colorScale);

rowChart.width(500)
    .height(500)
    .dimension(neighborhoodDimension)
    .group(neighborhoodGroup);

dc.renderAll();

var clickChart = d3.select("#pieChart")
clickChart.on("click",function(e){
      console.log(this)
      console.log(d3.select(this.parentNode))
})

I am trying to find a way to reference the specific path/bar/etc that I am clicking. So in the fiddle example I want to be able to grab the City that I am clicking, is that possible?

JSFiddle


Solution

  • Instead of selecting the <div>, just select the paths and get the datum (the first argument) inside the "click" function:

    var clickChart = d3.selectAll("path").on("click", function(e) {
        console.log(e.data.key)
    })
    

    Here is your fiddle: http://jsfiddle.net/1sbrng9n/