A resize event is dispatched when the browser window changes size. Listening for it lets a visualization respond to desktop window changes and mobile device orientation changes. section 9.2
Use the event to update responsive chart elements:
- Read the current width from window.innerWidth. section 9.2.1
- Store the width and pass it to a D3 linear scale that produces an appropriate font size. section 9.2.1 section 10.2.1
- Call the same resizeChart() function at page load and after every resize, avoiding duplicated update logic. section 9.2.1
- Update related positions and margins when larger labels need additional room. section 10.2.1
Responsive chart labels
A D3 line chart can listen for window resize, refresh windowWidth, and apply fontSizeScale(windowWidth) to its text elements. On small screens, the scale increases label size; on larger screens, it reduces it. Testing by resizing the browser reveals the change immediately. section 9.2.1 section 10.2.1
const resizeChart = () => {
d3.selectAll("#line-chart text") #1
.style("font-size", `${fontSizeScale(
windowWidth)}px`);
};
window.addEventListener("resize", () => { #2
windowWidth = getWindowWidth();
resizeChart();
});
The listing shows the complete resize listener, including width refresh and the call to resizeChart(). section 9.2.1
