Skip to content

Instantly share code, notes, and snippets.

Last active February 9, 2016 02:13
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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">
div {
border: solid 1px #000;
background: #eee;
text-align: center;
margin: 10px;
padding: 10px;
width: 240px;
.active {
background: lightcoral;
<div>drag me</div>
<div>drag me too</div>
<div>then drag me</div>
<script src="//"></script>
d3.selectAll("div").on("mousedown", function() {
var div =
.classed("active", true);
var w =
.on("mousemove", mousemove)
.on("mouseup", mouseup);
d3.event.preventDefault(); // disable text dragging
function mousemove() {
function mouseup() {
div.classed("active", false);
w.on("mousemove", null).on("mouseup", null);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment