You can use drag.behaviour to add drag and drop events to elements.
1) Create a function to handle the drag event (of type d3.event ):
function dragmove(d) {
d3.select(this)
.style("top", ((d3.event.sourceEvent.pageY) - this.offsetHeight/2)+"px")
.style("left", ((d3.event.sourceEvent.pageX) - this.offsetWidth/2)+"px")
}
2) Create a drag and drop behavior using the above function as a handler:
var drag = d3.behavior.drag()
.on("drag", dragmove);
3) Bind it to an element or set of elements, using .calld3 to select:
d3.select("body").append("div")
.attr("id", "draggable")
.text("Drag me bro!")
.call(drag)
Try: http://jsfiddle.net/HvkgN/2/
Here is the same example adapted for the svg text element :
function dragmove(d) {
d3.select(this)
.attr("y", d3.event.y)
.attr("x", d3.event.x)
}
var drag = d3.behavior.drag()
.on("drag", dragmove);
d3.select("body").append("svg")
.attr("height", 300)
.attr("width", 300)
.append("text")
.attr("x", 150)
.attr("y", 150)
.attr("id", "draggable")
.text("Drag me bro!")
.call(drag)
source
share