Question

I want to enable dragging in a d3.js force layout. When dragging a circle and release the mouse button, I want to call a specific function via callback, like this:

this.force = d3.layout.force()
    .nodes(this.nodes)
    .size([this.width, this.height]);

// enable dragging
this.circle
    .call(this.force.drag)
    .on("dragend", function() {
        console.log("You should see this, when releasing a circle.");
    })
    .on("mouseup.drag",function(d,i) {
        console.log("Or see this.");
    });

Unfortunately the event is never fired/consumed completely by the force.drag handler. So how can I execute a given callback function in a d3 force layout at the end of a drag?

Was it helpful?

Solution

You are not calling the "dragend" event on this.force.drag here. This also depends on how you have defined this.force.drag.

This should work for you

myCustomDrag = d3.behavior.drag()
    .on("dragstart", function(d,i){
        //do something when drag has just started
    })
    .on("drag", function(d,i){
        //do something while dragging
    })
    .on("dragend", function(d,i){
        //do something just after drag has ended
    });

In the above code, just use call(myCustomDrag) on an element (circle here) on which you want this drag behaviour to be present.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top