d3 drag and drop

by 8indaas

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.16/d3.min.js"></script>

CSS

.link {
  stroke: #ccc;
}

.node text {
  pointer-events: none;
  font: 10px sans-serif;
}

.dropzoneEnable {
  opacity: 0.2;
}

.dropzoneDisable {
  opacity: 1;
}

JavaScript

var width = 460,
height = 300,
radius = 20,
dropZoneWidth = 250,
dropZoneHeight = 150;

var nextSlot = [0,0];

var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);


var drag = d3.behavior.drag()
.origin(function() {
var t = d3.select(this)
//debugger;
console.log(t.attr("x") + ":" +t.attr("y") )
return {x: t.attr("x") + d3.transform(t.attr("transform")).translate[0],
                    y: t.attr("y") + d3.transform(t.attr("transform")).translate[1]};
})
.on("drag", dragmove)
.on("dragstart", dragStart)
.on("dragend", dragEnd);

var rect = svg.append("rect")
.attr("class", "dropzone")
.attr("x", 10)
.attr("y", 10)
.attr("width", dropZoneWidth)
.attr("height", dropZoneHeight)
.style("fill", "steelblue");

var g = svg.append("g")
.style("cursor", "pointer")
.call(drag);

var txt = g.append("text")
      .attr("x", 12)
      .attr("y", 200)
      .text("Neque porro");
      
var txtWidth = d3.select("text")[0][0].getBBox().width;
      
var r1 = g.append("rect")
.attr("x", 10)
.attr("y", 210)
.attr("height", 20)
.attr("width", txtWidth)
.style("fill", "white")
.style("stroke", "black");


//debugger;

function dragmove() {
console.log("dragmove called + (" + d3.event.x + "," + d3.event.y + ")");

if(d3.event.x < dropZoneWidth && d3.event.y < dropZoneHeight) {
	d3.select(".dropzone").classed("dropzoneDisable", false);
  d3.select(".dropzone").classed("dropzoneEnable", true);
  console.log("within drop zone");
} else {
	d3.select(".dropzone").classed("dropzoneDisable", true);
  d3.select(".dropzone").classed("dropzoneEnable", false);
	console.log("outside drop zone");
}
d3.select(this).attr("transform", function(d) { 
  return "translate(" + d3.event.x + "," + d3.event.y + ")"; 
});
}

function dragStart() {
console.log("dragStart called");
}

function dragEnd() {
	d3.select(".dropzone").classed("dropzoneDisable", true);
  d3.select(".dropzone").classed("dropzoneEnable", false);
  //if within the drop zone, snap to the nextSlot...