Benjamin Schroeder Benjamin Schroeder - 5 months ago 47
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:

And here is the map I'm working on:

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:

var stateNameId =;
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')
.on('mouseout', function() {
tooltip.classed('hidden', true);


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(; //add this to the top

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