liveBook · Manning

Resize event

As explained in D3.js in Action, Third Edition

A resize event is a browser event dispatched when the dimensions of a window or other resizable object change.

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

How D3.js in Action, Third Edition covers it

How deep it goes
Explains event listening, width measurement, shared updates, scaling, and label repositioning without covering event internals.
Examples
Uses a responsive line chart whose text labels, axis ticks, positions, and margins change with screen width.
What you can do after
Apply it via JavaScript and D3 to update chart styling and layout after every browser resize.
How it connects
Connects responsive visualization, CSS media queries, D3 scales, SVG, and accessibility.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.