Prevent click action when dragging a D3 Node

4k Views Asked by At

I'm able to click on a D3 node to get an alert(); message. I'm able to drag the D3 node too, but dragging also triggers the click behavior when the mouse is released.

Is there a way to prevent the click behavior after dragging the node?

This is where I call drag:

var node = svg.selectAll(".node")
    .data(graph.nodes)
    .enter()
  .append("g")
    .attr("transform", function(d){return "translate("+d.x+","+d.y+")"})
    .on("click", function(d){
        if(d.user_id != "" && d.user_id != null){
            parent.parent.openUserProfile(d.user_id);
        }
    })
    .call(force.drag);

One answer below suggests adding something like this code (below), but I think that the code above also has to be modified to make them work together.

var drag = d3.behavior.drag();
drag.on("dragend", function() {
  d3.event.sourceEvent.stopPropagation(); // silence other listeners
});
1

There are 1 best solutions below

3
On BEST ANSWER

As the docs has mentioned:

When combining drag behaviors with other event listeners for interaction events, you may also consider stopping propagation on the source event to prevent multiple actions.

var drag = d3.behavior.drag();
selection.call(drag);

drag.on("dragend", function() {
  d3.event.sourceEvent.stopPropagation(); // silence other listeners
});