Don't be a drag

by Laurie Skelly

HTML

<p>This demonstrates some click and drag behavior.</p>

<p>The function <code>drag</code> describes what to do when you click on an object and start dragging, and what to do when you let go.</p>

CSS

p{
    font-family:sans-serif;
    font-size:12px;
}

JavaScript

var u = 100;
var s = 400;

var svg = d3.select('body')
    .append('svg')
    .attr('height',s)
    .attr('width',s)
    .style('background-color','aliceblue')

var drag = d3.behavior.drag()
    .origin(function(d){return d;})
    .on('drag',function(d){
        d3.select(this)   
            .attr('x',d.x=d3.event.x)
            .attr('y',d.y=d3.event.y)
    })
    .on('dragend',function(d){
        d3.select(this)
        .transition()
        .duration(200)
        .ease('poly(5)')
        .attr('x',d.x=20+Math.random()*(s-d.s-20))
        .attr('y',d.y=20+Math.random()*(s-d.s-20))
        console.log(d)
    })    

svg.selectAll('rect')
    .data([{'x':u,'y':u,'s':u*2/3,'c':'lavender'},
           {'x':5*u/2,'y':3*u/2,'s':u,'c':'darkgray'}])
    .enter().append('rect')
    .attr('x',function(d){return d.x})
    .attr('y',function(d){return d.y})
    .attr('height',function(d){return d.s})
    .attr('width',function(d){return d.s})
    .style('fill',function(d){return d.c})
    .call(drag)