Download: javascript, html, data

Selecting Countries

Next we'll add an interactive element: allowing the user to select a country, and displaying the record count from that country. This is simple to implement in our .js using the .on("click",...) method:

.on('click', function(d){
	selectionID = null;
	var clickSelection =
	clickSelection.classed("selected", function(d){
		if (clickSelection.classed("selected")){
			return false	//if already selected, unselect it
		} else {
			selectionID = parseInt(;
			selectionName = country[parseInt(];
			d3.selectAll(".selected").classed("selected", false);	//clear previous selection
			clickSelection.moveToFront()	//bring selected country to front of draw order
			return true}

There are just a few key things we do in here: add the class "selected" to the clicked object, which allows us to change its visual properties in our CSS, store some information about the country selected so we can display its name and record count elsewhere, and finally, if selecting a new country, move that object to the front of the draw order (otherwise the borders will be inconsistent, as borders from neighboring countries higher in the draw order will overlap our selected country's borders).

Hovering & Tooltips

Similarly, we can highlight countries on mouseover using the .on('mouseover', ... ) and .on('mouseout', ... ) methods, by adding and removing respectively the "highlighted" class.

Finally, we add a tooltip for the hover-highlighted country. I followed this basic example, but there are many other implementations to choose from. First we set up rectangle object and text:

var tooltip ="#map")
	.attr("class", "tooltip")
	.style("display", "none");
  .attr("height", 20)
  .attr("fill", "white")
  .style("opacity", 0.5);

  .attr("x", 5)
  .attr("dy", "1.2em")
  .style("text-anchor", "left")
  .attr("font-size", "12px")
  .attr("font-weight", "bold");

Then display or hide the tooltip on mouseover and mouseout respectively. Update the text and rectangle width on mouseover, and translate the tooltip on mousemove so it follows the cursur:

.on('mousemove', function(d) {
	var xPosition = d3.mouse(this)[0] + 10;
	var yPosition = d3.mouse(this)[1] - 25;
	tooltip.attr("transform", "translate(" + xPosition + "," + yPosition + ")");
Files used in this visualization: javascript, html, data