Created
April 22, 2017 16:00
-
-
Save flunky/3336e53db8923cd17e85c5887859d1a2 to your computer and use it in GitHub Desktop.
D3 Tooltip Example
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> | |
<script src="http://d3js.org/d3.v4.min.js"></script> | |
<style> | |
.chart rect { fill: steelblue; } | |
#tooltip { | |
opacity: 0; | |
position: absolute; | |
text-align: center; | |
width: 60px; height: 40px; | |
background: white; | |
border: 0px; | |
} | |
</style> | |
<html><body> | |
<p>Here are the magic numbers from Lost: <span id="data"></span></p> | |
<svg class="chart"></svg> | |
<div id="tooltip"></div> | |
<script> | |
var width = 120, height = 300; | |
var data = [4,8,15,16,23,42]; | |
document.getElementById("data").innerHTML = data; | |
var x = d3.scaleLinear().domain([0,6]).range([0,width]); | |
var y = d3.scaleLinear().domain([0,42]).range([height,0]); | |
var tooltip = d3.select("#tooltip"); | |
d3.select(".chart") | |
.attr("width",width) | |
.attr("height",height) | |
.selectAll("rect") | |
.data(data) | |
.enter().append("rect") | |
.attr("width",19) | |
.attr("height",function(d) { return height - y(d); }) | |
.attr("x",function(d,i) { return x(i); }) | |
.attr("y",function(d) { return y(d); }) | |
.on("mouseover", function(d,i) { | |
tooltip.style("opacity", 1) | |
.style("left",(d3.event.pageX)+"px") | |
.style("top",(d3.event.pageY)+"px") | |
.html("Item #"+i+" is "+d); | |
}) | |
.on("mouseout", function() { tooltip.style("opacity", 0) }) | |
</script> | |
</body></html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment