Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3js Force Network: Ctrl-Click node to external link?

Tags:

d3.js

I have a simple force network graph where I want to use ctrl-Click to allow navigation to an external URL. See the JS Fiddle here:

https://jsfiddle.net/NovasTaylor/o1qesn6k/

I successfully hard-coded a link for all nodes using d3.event.ctrlKey under the on click event, as in:

 var nodes = svg.selectAll("g.node")
                 .data(dataset.nodes)
                 .enter()
                 .append("g")
                 .attr("class", "node")
                 .on("dblclick", dblclick)
                 .on("click", function () {
                     if (d3.event.ctrlKey) {
                     location.href = 'http://www.google.com';
                     }
                  })
                 .call(drag);

I instead want to use a URL specified for each node in the source data as d.url (see the Fiddle - the value is available for node "B").

I've seen some references on coding this with an tag but was unable to get the click event to fire navigation to the URL. The target URL should open in the same window, replacing the force network graph.

Your assistance would be greatly appreciated.

Cheers,

Tim

UPDATE: With Lars' advice, the code that solves the problem is: :

  var nodes = svg.selectAll("g.node")
      .data(dataset.nodes)
      .enter()
      .append("g")
      .attr("class", "node")
      .on("dblclick", dblclick)
      .on("click", function (d) {
         if (d3.event.ctrlKey) {
          location.href = d.url;
      }
  })
like image 641
Tim Avatar asked Mar 05 '15 17:03

Tim


1 Answers

Pretty much all of the callback functions in D3 are given the data bound to the element as an argument. You can reference this in the definition of the function and set values dynamically. In your case, it would be

.on("click", function (d) {
     if (d3.event.ctrlKey) {
      location.href = d.url;
  }
like image 51
Lars Kotthoff Avatar answered Sep 21 '22 20:09

Lars Kotthoff