Skip to content

Instantly share code, notes, and snippets.

@pbogden
Last active December 20, 2015 14:49
Show Gist options
  • Save pbogden/6150094 to your computer and use it in GitHub Desktop.
Save pbogden/6150094 to your computer and use it in GitHub Desktop.
SVG shapes

Multiple overlapping shapes with event-driven opacity changes and a tooltip

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>shapes & tips</title>
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
<style>
body, svg {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
position: relative;
}
.line, rect {
stroke: black;
stroke-width: 2px;
}
.tooltip {
margin: 30px 30px 30px 30px;
background-color: lightgray;
border-style: solid;
padding: 10px 10px 10px 10px;
font-size: 1.5em;
position: absolute;
z-index: 100;
}
</style>
</head>
<body>
<script>
var width= 960, height=500;
// contrived pre-scaled data for use w/default accessors
var data = [[ 0, 400- 0], [100, 400-133], [400, 400-178],
[600, 400- 89], [800, 400-400], [960, 400-311]];
var line = d3.svg.line(); // SVG line generator using default accessors
var g = d3.select("body").append("svg")
.attr('width', width)
.attr('height', height)
.append("g");
g.append("rect") // plot a rectangle first
.attr("fill", "red")
.style("fill-opacity", 1) // initialize fill-opacity here, or first toggle won't work
.attr("width", width)
.attr("height", height)
.on("mouseover", toggle)
.on("mouseout", toggle);
g.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line)
.style("fill-opacity", 1)
.on("mouseover", toggle)
.on("mouseout", toggle);
data.forEach(function(d) { d[0] += 90 });
g.append("path")
.datum(data)
.attr("class", "line")
.attr("fill", "blue")
.attr("d", line)
.style("fill-opacity", 1)
.on("mouseover", showTooltip)
.on("mousemove", moveTooltip)
.on("mouseout", hideTooltip);
// Create the tooltip div (there's only one)
var tooltip = d3.select("body")
.append("div")
.attr("class", "tooltip")
.style("visibility", "hidden")
.text("a simple tooltip");
function toggle() {
if ( this.style.fillOpacity < 1 ) {
this.style.fillOpacity = "1";
} else {
this.style.fillOpacity = "0.5";
};
}
function showTooltip(d) {
this.style.fillOpacity = "0.5";
tooltip.style("visibility", "visible");
tooltip[0][0].innerHTML = "Hello,<br>world!";
tooltip.style("top", (d3.event.pageY-10)+"px")
.style("left",(d3.event.pageX+20)+"px");
};
function moveTooltip(d) {
tooltip.style("top", (d3.event.pageY-10)+"px")
.style("left",(d3.event.pageX+20)+"px");
};
function hideTooltip(d) {
this.style.fillOpacity = "1";
tooltip.style("visibility", "hidden");
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment