let main = d3.select('.testing-chart-container') main.append('div').attr('class', 'testing-chart-title testing-bold').text('COVID-19 Tests Per Million (June 18)') let container = main.append('div').attr('class', 'testing-chart') main.append('div').attr('class', 'testing-source').html(`Source: `) let countryArray = [] class Country { constructor(name, tests, totalTests, highlight=false) { this.name = name; this.tests = tests; this.totalTests = totalTests; this.highlight = highlight; countryArray.push(this) } percent() { return `${100*this.tests/maxTests}%` } } new Country('Canada', 59753, 2254481, true) new Country('UAE', 303467, 3000000) new Country('Denmark', 148410, 859514) new Country('Spain', 103232, 4826516) new Country('UK', 104930, 7121976) new Country('Italy', 78945, 4773408) new Country('Australia', 74863, 1908154) new Country('USA', 79329, 26252588 ) new Country('Germany', 60038, 5029696) new Country('Peru', 43028, 1417911) countryArray.sort((a, b) => a.tests - b.tests) let maxTests = d3.max(countryArray, d => d.tests); let tooltip = container.append('div').attr('class', 'tooltip') countryArray.forEach((country, i) => { container.append('div').attr('class', `testing-country ${country.highlight ? 'testing-bold highlight' : ''}`).text(country.name) let barContainer = container.append('div').attr('class', 'testing-bar-container') let bar = barContainer.append('div').attr('class', `testing-bar ${country.highlight ? 'highlight' : ''}`) bar.style('width', 0).transition().duration(1200 + country.tests/200).style('width', country.percent()) bar.on('mousemove', function(e) { tooltip.style('display', 'block') tooltip.html(`
${country.name}
Total Tests: ${country.totalTests.toLocaleString()}
`); let node = container.node(); let [x, y] = d3.mouse(node) let [w, h] = [tooltip.node().offsetWidth, tooltip.node().offsetHeight] let [cW, cH] = [node.offsetWidth, node.offsetHeight] //console.log([x, y]) tooltip.style('left', `${Math.min(cW - w, Math.max(0, x - w/2))}px`) tooltip.style('top', `${Math.min(cH - h, Math.max(0, y > cH - h - 50? y - 5 - h : y + 30))}px`) }) .on('mouseout', function(e) { tooltip.style('display', 'none') }) let num = bar.append('div').attr('class', 'testing-number').text(country.tests.toLocaleString()) num.style('opacity', 0).transition().duration(1200 + country.tests/200).style('opacity', 1) })