Currently I am creating my own force drag feature using d3js. I stumbled upon a fantastic example here which covers most of what I need:
However, I have encountered a problem that I am struggling to solve due to my limited knowledge of d3js.
I am attempting to merge two functionalities: - Dragging the nodes so they remain in place when released - Adding names on top of the nodes that move with them when dragged
The issue arises when I drag the nodes after loading the diagram - the text labels do not update their position.
Here is the snippet of code responsible for the labeling, and you can find the full jsfiddle here:
Code snippet for labeling:
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("g")
.attr("class", "node")
.call(force.drag);
node.append("circle")
.attr("r", 8)
.style("fill", function (d) {
return color(d.group);
})
node.append("text")
.attr("dx", 10)
.attr("dy", ".35em")
.text(function(d) { return d.name })
.style("stroke", "gray");
force.on("tick", function () {
// rest of tick function ...
});
// remaining code snippet ...
And here is the code snippet for pinning the nodes, with full jsfiddle available here:
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 8)
.style("fill", function (d) {
return color(d.group);
})
.on('dblclick', releasenode)
.call(node_drag);
// additional drag functions ...
I have combined both snippets, but the labels do not follow the nodes when pinned. The issue occurs at the point where I initialize both functionalities:
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("g")
.attr("class", "node")
.style("fill", function (d) {
// fill color logic ...
})
.call(force.drag) // Take care of labels
.on('dblclick', connectedNodes) // Additional code
// more event listeners ...
node.append("circle")
.attr("r", 8)
.style("fill", function (d) {
// fill color logic ...
})
Everything works fine when using each functionality separately. How can I activate both simultaneously? Is there an alternative method to pin the nodes successfully while updating the labels accordingly?