Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active February 9, 2016 02:13
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 mbostock/4198499 to your computer and use it in GitHub Desktop.
Save mbostock/4198499 to your computer and use it in GitHub Desktop.
Capturing Mousemove
license: gpl-3.0

This example demonstrates a simple technique for capturing mousemove and mouseup events that are initiated by a mousedown on an element of interest. The mousemove and mouseup listeners are registered on the window when the first mousedown event is received; thus, these listeners are automatically scoped to the initiating element (div), while still being able to receive mouse events from anywhere in the current window. When the mouseup event is received, the window listeners are deleted.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
div {
border: solid 1px #000;
background: #eee;
text-align: center;
margin: 10px;
padding: 10px;
width: 240px;
}
.active {
background: lightcoral;
}
</style>
<div>drag me</div>
<div>drag me too</div>
<div>then drag me</div>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
d3.selectAll("div").on("mousedown", function() {
var div = d3.select(this)
.classed("active", true);
var w = d3.select(window)
.on("mousemove", mousemove)
.on("mouseup", mouseup);
d3.event.preventDefault(); // disable text dragging
function mousemove() {
div.text(d3.mouse(div.node()));
}
function mouseup() {
div.classed("active", false);
w.on("mousemove", null).on("mouseup", null);
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment