D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
sergeiwallace
Full window
Github gist
New York State D3 Counties Highlight & Hover
<!DOCTYPE html> <meta charset="utf-8"> <style> @import url(styles.css); </style> <script src="//d3js.org/d3.v3.min.js"></script> <script src="//d3js.org/queue.v1.min.js"></script> <body> <div id="map_container"> <script> var mw = 800; // map container width var mh = 600; // map container height var toolTipVisible = true; var svg = d3.select("#map_container") .append("svg") .attr({"width": mw, "height": mh}); var data; var ny; // Define the div for the tooltip var div = d3.select("body").append("div") .attr("class", "tooltip") .style("opacity", 0); queue() .defer(d3.csv, "highlight.csv", data) .await(ready); function ready(error, data) { if (error) throw error; d3.xml("ny.svg", "image/svg+xml", function(error, xml) { /* embed the SVG map */ if (error) throw error; var svgMap = xml.getElementsByTagName("g")[0]; /* set svgMap to root g */ ny = svg.node().appendChild(svgMap); /* ny map */ svg.selectAll("#counties").selectAll("polygon") .on("click", handleClick) .on("mouseover", handleMouseOver) .on("mouseout", handleMouseOut); svg.selectAll("#counties").selectAll("path") .on("click", handleClick) .on("mouseover", handleMouseOver) .on("mouseout", handleMouseOut); d3.map(data, function(d) { console.log(d.county) d3.select("#"+d.county).attr("class", "highlight"); }); }); } function handleClick(d, i){ id = d3.select(this).attr('id'); } function handleMouseOver(d){ if (d3.select(this).classed("active")) return; /* no need to change class when county is already selected */ if (!d3.select(this).classed("highlight")){ d3.select(this).attr("class", "hover"); } if(toolTipVisible){ div.transition() .duration(200) .style("opacity", .9); div .html(d3.select(this).attr('id').replace("_", " ")) .style("left", (d3.event.pageX) + "px") .style("top", (d3.event.pageY - 5) + "px"); } } function handleMouseOut(d){ if (d3.select(this).classed("active")) return; if (!d3.select(this).classed("highlight")){ d3.select(this).attr("class", "st0"); } div.transition() .duration(200) .style("opacity", 0); div .html('') .style("left", "0px") .style("top", "0px"); } </script> </body> </html>
https://d3js.org/d3.v3.min.js
https://d3js.org/queue.v1.min.js