Skip to content

Instantly share code, notes, and snippets.

@pnavarrc
Last active December 15, 2015 02:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pnavarrc/5190856 to your computer and use it in GitHub Desktop.
Save pnavarrc/5190856 to your computer and use it in GitHub Desktop.
Example of Drag Behavior in D3
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Drag Behavior Demo</title>
</head>
<script src="http://d3js.org/d3.v3.min.js"></script>
<body>
<script type="text/javascript">
var width = 600,
height = 600,
div = d3.select('body').append('div'),
svg = div.append('svg'),
bar = svg.append('rect'),
drag = d3.behavior.drag();
svg.attr('width', width)
.attr('height', height);
// This function is called on drag
function move(d) {
var bar = d3.select(this);
// Update the position of the bar by adding the drag distance in each coordinate
bar.attr('x', parseInt(bar.attr('x'), 10) + d3.event.dx)
.attr('y', parseInt(bar.attr('y'), 10) + d3.event.dy);
}
drag.origin(Object)
.on('drag', move);
bar = svg.append('rect'),
bar.attr('x', (width - 200) / 2)
.attr('y', (height - 200) / 2)
.attr('width', 200)
.attr('height', 200)
.attr('fill', '#98CFEA')
.call(drag);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment