2

In the d3js bubble chart shown in the following link : http://www.nytimes.com/interactive/2012/09/06/us/politics/convention-word-counts.html?_r=0#!

the bubble gets highlighted when it is clicked . I want to implement that feature in my d3js bubble chart. Does anyone know how to do it? Thanks in advance .

salsa111
  • 171
  • 1
  • 15

2 Answers2

1

When you click the bubble, the g-selected class is added to the nodes. That changes the css that applies from

.g-node .g-democrat {
    fill: #c5d7ea;
}
.g-node .g-republican {
    fill: #f9caca;
}

to

.g-node.g-selected .g-democrat {
    fill: #99c0e5;
    stroke: #6081a3;
    stroke-width: 1.5px;
}
.g-node.g-selected .g-republican {
    fill: #fda4a7;
    stroke: #af5e61;
    stroke-width: 1.5px;
}

Adding a class to a clicked element is pretty straightforward. The class is added using the selection.classed method.

node.classed("g-selected", function(d) { return d === topic; });

If you are looking at the source, look at the updateActiveTopic function.

The code in your fiddle is quite a bit simpler than the example you linked. I would change the part where you create the circle elements so that it uses css, rather than inline style, i.e.

circle {
    fill: green;
}

instead of

 .style("fill", function (d, i) {
      return "green";
 })

Now, you'll add a click handler to the circles:

circle.on("click", function(d) {
        // remove selected class from all circles that have it
        circle.classed('selected', false);

        //add the selected class to the element that was clicked
        d3.select(this).classed('selected', true)
    });

and a style to highlight the circle when it is selected

circle.selected {
    fill: blue;
    stroke: black;
    stroke-width: 1.5px;
}

See the fiddle for the complete example.

Steve Clanton
  • 4,064
  • 3
  • 32
  • 38
0

Here is a basic start to what you're trying to achieve. You need to start by adding a click function to your circle.

circle.on('click', function(d){
    //grabs all the circles from your array
    var allCircles = circle[0]

    //Used to cycle through to see if any of them are classed with the 'selected' class'
    for (var i=0; i<allCircles.length; i++){
        d3.select(allCircles[i]).classed('selected', false)
        d3.select(allCircles[i]).attr('style', 'fill: rgb(0,128,0);')
    }

    //Set the circle you clicked on to have no inline style and classed to 'selected'
    d3.select(this).attr('style', '')
    d3.select(this).classed('selected', true)
})

I've updated the fiddle so you can see. You can edit the CSS however you need. Currently, it just fills the circle with a blue fill, but you can use CSS similar to the example you posted.

BDD
  • 665
  • 17
  • 31