Preparing the Tooltip
We will implement a clever trick for detecting hover events on a thin element by layering it with an invisible element.
We'll cover the following...
We are going to create the tooltip for the line chart. It is difficult to determine the prices for individual dates. The axes help, but they do not paint the full picture. Our readers may want to see the price of a stock sold on a specific date. Creating a tooltip for a line chart will come with some challenges. We will discuss those challenges as they arise.
Adding UI elements
There are a few things we are going to need. First, we need to add some UI elements that will change based on where the reader is hovering. We are going to need an element for the tooltip. We will also add a dot that will be positioned over the line to show the reader where they are on the line. Let’s add these elements.
We will start with the tooltip. In the HTML section, we are going to create the tooltip with plain HTML. Inside the #chart
element, we will add the following:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>D3 Line Chart</title><!-- <link rel="stylesheet" type="text/css" href="style.css" /> --></head><body><div id="chart"><div id="tooltip"><div class="price"></div><div class="date"></div></div></div><script src="https://d3js.org/d3.v6.js"></script><!--- <script src="app.js"></script> --></body></html>
The elements have already been styled and some default styles are provided in the style section. We can move on to selecting these elements with D3. Below the other selections in our script, we will add the following:
// Draw Imageconst svg = d3.select('#chart').append("svg").attr("width", dimensions.width).attr("height", dimensions.height)const ctr = svg.append("g") // <g>.attr("transform",`translate(${dimensions.margins}, ${dimensions.margins})`)const tooltip = d3.select("#tooltip")
We are storing the selection for the tooltip in a variable called tooltip
.
We are going to create another selection for the dot. The name of the variable will be called tooltipDot
. Its value will be the ctr.append()
function. We are going to append a <circle>
...