window.print With beforeprint State Swap
Open the print dialog with window.print() and use beforeprint/afterprint listeners to swap chart markup for print-friendly tables and restore it after.
Code
// window.print() opens the print dialog; beforeprint/afterprint bracket it so
// screen-only state can be swapped for a print-friendly one and restored.
const chart = document.querySelector<HTMLElement>('#chart-summary');
const table = document.querySelector<HTMLElement>('#chart-table');
window.addEventListener('beforeprint', () => {
if (!chart || !table) return;
chart.hidden = true;
table.hidden = false; // paper needs the numbers, not the visualization
});
window.addEventListener('afterprint', () => {
if (!chart || !table) return;
chart.hidden = false;
table.hidden = true;
});
document.querySelector<HTMLButtonElement>('#print-btn')?.addEventListener('click', () => {
window.print();
});Inside the code
The file’s state is a handful of top-level bindings: chart, table.
What to watch for
- Dependency-free as written — nothing in a registry, nothing in a lockfile.
- A browser is the runtime here:
document,windoware not available in Node. - The guard
!chart || !tablecuts the flow short with an earlyreturnwhen its condition holds.
Statements that matter
document.querySelector<HTMLButtonElement>('#print-btn')?.addEventListener('click', () => {
window.print();
});
window.addEventListener('beforeprint', () => {
if (!chart || !table) return;
chart.hidden = true;
table.hidden = false; // paper needs the numbers, not the visualization
});
window.addEventListener('afterprint', () => {
if (!chart || !table) return;
chart.hidden = false;
table.hidden = true;
});
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does window.print With beforeprint State Swap run in plain Node.js?
- No — it touches `document` and `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.