Skip to content

Instantly share code, notes, and snippets.

@rentzso
Forked from mbostock/.block
Last active August 29, 2015 14:21
Show Gist options
  • Save rentzso/75652b5e3373cd1d9efd to your computer and use it in GitHub Desktop.
Save rentzso/75652b5e3373cd1d9efd to your computer and use it in GitHub Desktop.

This example demonstrates mouseenter and mouseleave events. Mouseenter and mouseleave events are triggered only when the mouse enters or leaves the parent container; unlike mouseover and mouseout, they are not triggered when the mouse moves between descendant elements. This makes it easier to listen for when the mouse enters a group of elements and avoid unnecessary flickering.

For browsers that do not yet support mouseenter and mouseleave events, D3 provides a polyfill on top of the mouseover and mouseout events.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
rect {
fill-opacity: .1;
stroke: #000;
shape-rendering: crispEdges;
}
rect:hover {
stroke: red;
}
text {
pointer-events: none;
text-anchor: middle;
font: 12px sans-serif;
text-shadow: 0 1px 0 #fff, 0 -1px 0 #fff, 1px 0 0 #fff, -1px 0 0 #fff;
}
text.mouseenter,
text.mouseleave {
fill: red;
font-weight: bold;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
.call(nest, 6, 30)
.on("mouseenter", flash("mouseenter", "-1em"))
.on("mouseover", flash("mouseover", "0"))
.on("mouseout", flash("mouseout", "1em"))
.on("mouseleave", flash("mouseleave", "2em"))
.on("click", flash("click","3em"));
function flash(name, dy) {
return function() {
d3.select(this).append("text")
.attr("class", name)
.attr("transform", "translate(" + d3.mouse(this) + ")")
.attr("dy", dy)
.text(name)
.transition()
.duration(1500)
.style("opacity", 0)
.remove();
};
}
function nest(svg, levels, step) {
var g = svg.append("g");
g.append("rect")
.attr("x", -(levels + 1) * step)
.attr("y", -(levels + 1) * step)
.attr("width", (levels + 1) * step * 2)
.attr("height", (levels + 1) * step * 2);
if (levels > 0) g.call(nest, levels - 1, step);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment