Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3.js Highlighting links on node selection

so first, I have data in the format the same as miserables.json below https://bl.ocks.org/mbostock/4062045

I would like to be able to make the link connected to my node red when I click the node. So the psuedo⁻code would be like

selectAll(.links)
if links.source=nodeID or links.target=nodeID
then links.color=red

But I have not be able to do it. My ultimate goal would be intergrate it with Arc diagram below http://bl.ocks.org/sjengle/5431779

like image 1000
Loredra L Avatar asked Jan 01 '26 03:01

Loredra L


2 Answers

Your pseudocode is a good start. You can use filter to implement the if condition in a selection. Note that the .source and .target of links are edited by d3, they are no longer the id of the nodes, but the node themselves:

thisNode = nodeObject; // where nodeObject is the javascript object for the node, it's probably called "d" in your function.
d3.selectAll(".link")
  .filter(function(d) {
     return (d.source === thisNode) || (d.target === thisNode);
   })
  .style("stroke", "red")
like image 115
tarulen Avatar answered Jan 04 '26 17:01

tarulen


Expanding on top of @laurent's answer, to "reset" color of links that potentially were painted red during a previous interaction:

thisNode = nodeObject; // where nodeObject is the javascript object for the node, it's probably called "d" in your function.
d3.selectAll(".link")
  .style("stroke",function(d) {
     return d.source === thisNode || d.target === thisNode ? "red" : "#888888";
   })
like image 36
Mehdi Avatar answered Jan 04 '26 16:01

Mehdi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!