Benjamin Schroeder Benjamin Schroeder - 3 months ago 17
Javascript Question

Map tooltips in the wrong location

I'm trying to include tooltips on a map I'm making in D3, imitating this code:
http://bl.ocks.org/lhoworko/7753a11efc189a936371

And here is the map I'm working on:
https://pantherfile.uwm.edu/schro333/public/2016_electoral_map/

As you can see here, I have tooltips working, and they display the correct name when the user hovers over a state, but the position relative to the cursor is really off. I'm not sure why this is.

Relevant code:

svgContainer.selectAll("pathCodes")
.data(json.features)
.enter()
.append("path")
.attr("id",
function(d){
var stateNameId = d.properties.name.toString();
stateNameId = stateNameId.replace(/\s+/g, '');
return stateNameId;
}) // this function returns the name of the state with spaces stripped and assigns it to individual polygon as id
.attr("d", pathCodes)
.attr("stroke", "black") // state outline color
.attr("stroke-width", "1") // state outline width
.attr("class", "noparty") // default to no party
.style("fill", politicalParties[0].color) // default fill is that of no party
/////////////
.on('mousemove', function(d) {
var mouse = d3.mouse(svgContainer.node());
tooltip.classed('hidden', false)
.attr('style', 'left:' + (mouse[0]) +
'px; top:' + (mouse[1]) + 'px')
.html(d.properties.name);
})
.on('mouseout', function() {
tooltip.classed('hidden', true);
});
/////////////

Answer

You get the wrong position because the X/Y position you are using is based off the SVG and not the actual location of the SVG on the page.

You can use

var loc = document.getElementById("states-map").getBoundingClientRect();
console.log(loc.top); //add this to the top

to get the offset. Not sure the d3 way to do it.