Skip to content

Instantly share code, notes, and snippets.

@codetricity
Last active October 11, 2018 13:29
Show Gist options
  • Save codetricity/7ced6f3b3c95d64e7d7467e430716a63 to your computer and use it in GitHub Desktop.
Save codetricity/7ced6f3b3c95d64e7d7467e430716a63 to your computer and use it in GitHub Desktop.
d3 minimal drag example

Minimal Drag Example

  1. new event called drag
  2. d3.drag() is similar to d3.zoom() in the previous example

Example

https://bl.ocks.org/codetricity/7ced6f3b3c95d64e7d7467e430716a63

Set Up

    var svg = d3.select("body").append('svg')
        .attr('width', '400')
        .attr('height', '400')
        .style('border', 'solid 1px');

Create Circle

    var circle = svg.append("circle")
        .attr("cx", 50)
        .attr("cy", 50)
        .attr('r', 20);

New event called drag

    var dragHandler = d3.drag()
        .on('drag', dragged);

new event handler

The function can have any name.

    function dragged() {
        var current = d3.select(this);
        current
            .attr('cx', d3.event.x)
            .attr('cy', d3.event.y);                   
            console.log(`${d3.event.x}, ${d3.event.y}`);
    }

Call event handler

    dragHandler(circle);

Additional Information

longer example is here.

Note that the color scheme in the longer example above is no longer valid as of d3 v5.

var svg = d3.select("body").append('svg')
.attr('width', '400')
.attr('height', '400')
.style('border', 'solid 1px');
var dragHandler = d3.drag()
.on('drag', dragged)
// .on('start', dragstarted);
var circle = svg.append("circle")
.attr("cx", 50)
.attr("cy", 50)
.attr('r', 20);
dragHandler(circle);
function dragged() {
var current = d3.select(this);
current
.attr('cx', d3.event.x)
.attr('cy', d3.event.y);
}
<head>
<meta charset='utf-8'>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script src='drag.js'></script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment