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;
}
})
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With