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.
Last active
February 9, 2016 02:13
-
-
Save mbostock/4198499 to your computer and use it in GitHub Desktop.
Capturing Mousemove
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: gpl-3.0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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