I have implemented the tooltip but for some reason it’s just showing
“undefined $undefined Billion” as the tooltip so it isn’t accessing the variables that I have defined or not accessing them properly.
Haven’t found anything online that suggests I’ve done anything wrong which makes me think this is maybe something to do with the new version of d3 changing something… or I’m just missing something. Any help would be appreciated as I simply do not understand how the way I’ve done it is wrong.
https://codepen.io/TheTubbyNinja/pen/KKaPbgX?editors=0010
//Design variables
var width = 800;
var height = 400;
var barWidth = width / 275;
//Chart creation
var svg = d3.select(".bar-chart").append("svg").attr("height", height + 60).attr("width", width + 100);
var barChart = svg.append("g");
var tooltip = d3.select(".bar-chart").append("div").attr("id", "tooltip").style("opacity", 0);
d3.json('https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json')
.then(data => {
//Data variables
var gdp = data.data.map((item) => item[1]);
var gdpMax = d3.max(gdp);
var dates = data.data.map((item) => item[0]);
//Scales
var yScale = d3.scaleLinear().domain([0, gdpMax]).range([height, 0]);
var xScale = d3.scaleTime().domain(d3.extent(dates, (d) => new Date(d))).range([0, width]);
var axisX = d3.axisBottom().scale(xScale);
var axisY = d3.axisLeft().scale(yScale);
//Bars
barChart
.selectAll("rect")
.data(gdp)
.enter()
.append("rect")
.attr("class", "bar")
.attr("transform", "translate(50,20)")
.attr("height", (d) => height - yScale(d))
.attr("width", barWidth)
.attr("x", (d, i) => barWidth * i)
.attr("y", (d) => yScale(d))
.attr("data-gdp", (d, i) => data.data[i][1])
.attr("data-date", (d, i) => data.data[i][0])
.on("mouseover", (d, i) => {
tooltip
.style("opacity", 1)
.html(dates[i] + "<br>" + "$" + gdp[i] + "Billion")
})
.on("mouseout", function () {
tooltip
.style("opacity", 0);
})
//X axis
barChart
.append("g")
.attr("id", "x-axis")
.attr("transform", "translate(50," + (height + 20) + ")")
.call(axisX);
//Y axis
barChart
.append("g")
.attr("id", "y-axis")
.attr("transform", "translate(50, 20)")
.call(axisY);
})
.catch((error) => console.log(error));