user1144596
user1144596

Reputation: 2088

Click event on d3 di-graph

we are using a D3 forced digraph from the following link:

http://bl.ocks.org/jose187/4733747

i was unable to figure out how to enable click on a node. did notice that we have the coordinates but not sure how to "attach" a click event handler.

any ideas would be most appreciated.

Upvotes: 0

Views: 64

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102194

In D3, the listeners are attached using selection.on:

Adds or removes a listener to each selected element for the specified event typenames.

So, for a click event, it's simple as this:

node.on("click", function(){
    //your code here
}

Check the demo with your code:

<script src="http://d3js.org/d3.v2.min.js?2.9.3"></script>
<style>

.link {
  stroke: #aaa;
}

.node text {
stroke:#333;
cursor:pointer;
}

.node circle{
stroke:#fff;
stroke-width:3px;
fill:#555;
}

</style>
<body>
<script>

var width = 400,
    height = 300

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

var force = d3.layout.force()
    .gravity(.05)
    .distance(100)
    .charge(-100)
    .size([width, height]);

 var json = {
  "nodes":[
		{"name":"node1","group":1},
		{"name":"node2","group":2},
		{"name":"node3","group":2},
		{"name":"node4","group":3}
	],
	"links":[
		{"source":2,"target":1,"weight":1},
		{"source":0,"target":2,"weight":3}
	]
};
  
  force
      .nodes(json.nodes)
      .links(json.links)
      .start();

  var link = svg.selectAll(".link")
      .data(json.links)
    .enter().append("line")
      .attr("class", "link")
    .style("stroke-width", function(d) { return Math.sqrt(d.weight); });

  var node = svg.selectAll(".node")
      .data(json.nodes)
    .enter().append("g")
      .attr("class", "node")
      .call(force.drag);

  node.append("circle")
      .attr("r","5");

  node.append("text")
      .attr("dx", 12)
      .attr("dy", ".35em")
      .text(function(d) { return d.name });
  
  node.on("click", function(d){
    alert("hello, I'm " + d.name)
    })

  force.on("tick", function() {
    link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
  });

</script>

Upvotes: 2

Related Questions