Search code examples
javascriptd3.jsdrag-and-dropdrag

Drag a div and see the item moving


Right now I'm trying to achieve the drag and drop functionality.

I have this.

var drag = d3.behavior.drag();
  drag.on('drag', function () {
    console.log("drag start");
  })
  drag.on('dragend', function () {
    console.log("drag stop");
  })

  selection = d3.select('.right.menu');
  selection.call(drag);

Which works, but now I want to see the div moving on the screen, right now I only get the consoles, how this can be done, or even better any guidance about how this method / event is named to do some research will be great.

Update

Current Solution.

var drag = d3.behavior.drag();
  drag.on('drag', function () {
console.log(selection);
    selection.style("left", d3.event.x+"px").style("top", d3.event.y+"px").style("position", "inherit");
  })
  drag.on('dragend', function () {
    console.log("drag stop");
  })

  selection = d3.select('.right.menu')
  selection.call(drag);

Solution

  • Here's a simple example of moving a div using css position:absolute and modifying the top and left offset according to the drag.

    appdiv.style("left", d3.event.x+"px").style("top", d3.event.y+"px");
    

    Fiddle