Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent click action when dragging a D3 Node

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
});
like image 566
user1515295 Avatar asked Jun 09 '15 05:06

user1515295


1 Answers

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
});
like image 124
Rohit416 Avatar answered Sep 23 '22 21:09

Rohit416