Skip to content

Instantly share code, notes, and snippets.

@timpulver
Forked from couchand/index.html
Created January 28, 2015 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save timpulver/d3fefb4fac2510cf81a8 to your computer and use it in GitHub Desktop.
Save timpulver/d3fefb4fac2510cf81a8 to your computer and use it in GitHub Desktop.
[D3.js, Click, Double-Click] Distinguish between click and double-click and use data
<!DOCTYPE html>
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js"></script>
<style>
body { margin:0; padding:0; }
#map { width:960px; height:500px; background:#000; }
</style>
</head>
<body>
<div id='map'></div>
<script>
function clickcancel() {
var event = d3.dispatch('click', 'dblclick');
function cc(selection) {
console.log(selection);
var down,
tolerance = 5,
last,
wait = null;
// euclidean distance
function dist(a, b) {
return Math.sqrt(Math.pow(a[0] - b[0], 2), Math.pow(a[1] - b[1], 2));
}
selection.on('mousedown', function() {
down = d3.mouse(document.body);
last = +new Date();
});
selection.on('mouseup', function() {
if (dist(down, d3.mouse(document.body)) > tolerance) {
return;
} else {
if (wait) {
window.clearTimeout(wait);
wait = null;
event.dblclick(d3.event);
} else {
wait = window.setTimeout((function(e) {
return function() {
event.click(e);
wait = null;
};
})(d3.event), 300);
}
}
});
};
return d3.rebind(cc, event, 'on');
}
var cc = clickcancel();
d3.select('#map')
.data([100])
.call(cc);
cc.on('click', function(el) {
console.log("click, data: ");
var me = d3.select(el.srcElement)
.style("background", "#aaa");
var d = me.data()[0];
console.log(d);
});
cc.on('dblclick', function(el) {
console.log("dblclick, data: ");
var me = d3.select(el.srcElement)
.style("background", "#ddd");
var d = me.data()[0];
console.log(d);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment