HTML onbeforeprint Attribute

Beginner
⏱️ 5 min read
📚 Updated: Jun 2026
🎯 3 Examples
Events & Handlers

Introduction

The onbeforeprint attribute is an inline event handler that runs JavaScript when the beforeprint event fires. That event occurs on the window when the browser’s print dialog opens or print preview starts. Use it to prepare the page for printing—for example hiding navigation, adding a temporary class, or updating content before the print layout is rendered. Pair it with onafterprint to restore the screen UI when the dialog closes. It does not mean the document was sent to a printer; it runs at the start of the print flow.

What You’ll Learn

01

Event handler

Inline JS.

02

beforeprint

Window event.

03

Dialog opens

Prepare layout.

04

+ afterprint

Prepare / restore.

05

addEventListener

Preferred way.

06

.onbeforeprint

Property API.

Purpose of onbeforeprint Attribute

The primary purpose of onbeforeprint is to run preparation logic before the user sees the print preview or print dialog. A common pattern hides navigation and sidebars in beforeprint and shows them again in afterprint. You might inject print-only headers, expand collapsed sections, or swap chart data for a static snapshot.

The old reference said the document was “sent to the printer.” That is inaccurate—beforeprint means the print UI is opening, not that output reached a printer. Treat it as “print flow starting” rather than “print succeeded.”

💡
Prefer addEventListener on window

Production code should use window.addEventListener("beforeprint", handler). Inline onbeforeprint on <body> works for learning but separates concerns less cleanly.

📝 Syntax

Set onbeforeprint on body or assign window.onbeforeprint:

onbeforeprint.html
<script>

  function handleBeforePrint() {

    document.body.classList.add("printing");

    console.log("Print dialog opening.");

  }

</script>



<body onbeforeprint="handleBeforePrint()">

  <button type="button" onclick="window.print()">Print</button>

</body>

Syntax Rules

  • Value is JavaScript code executed when the beforeprint event fires.
  • Event target is window; body.onbeforeprint maps to the same event.
  • Pair with onafterprint / afterprint for prepare-and-restore flows.
  • JavaScript: window.onbeforeprint = function() { … }.
  • Modern alternative: window.addEventListener("beforeprint", handler).
  • Triggered by window.print() or the user choosing Print from the browser menu.

💎 Values

The onbeforeprint attribute accepts a string of JavaScript code:

  • onbeforeprint="handleBeforePrint()" — Call a named function.
  • onbeforeprint="console.log('prepare')" — Inline statement.
  • JavaScript: window.onbeforeprint = () => { … } assigns the handler.
onbeforeprint-js.html
window.addEventListener("beforeprint", () => {

  document.body.classList.add("print-mode");

});

window.addEventListener("afterprint", () => {

  document.body.classList.remove("print-mode");

});

⚡ Quick Reference

EventWhen it firesHandler
beforeprintPrint dialog opensonbeforeprint
afterprintPrint dialog closesonafterprint
Open print UIwindow.print()User or script
Prepare UIIn beforeprint handlerAdd print-only classes
Print CSS@media print { … }Often enough alone

Applicable Elements

TargetSupported?Notes
windowYesPrimary event target
<body>YesInline onbeforeprint attribute
<img>, <form>NoNot print events

Examples Gallery

Inline onbeforeprint, addEventListener on window, and pairing with afterprint.

👀 Live Preview

Use Print on this page — when the dialog opens, the status updates:

Open the print dialog to trigger beforeprint.

Example — Inline onbeforeprint on body

Call a function when the print dialog opens:

inline-onbeforeprint.html
<body onbeforeprint="handleBeforePrint()">

  <button onclick="window.print()">Print</button>

</body>



<script>

  function handleBeforePrint() {

    console.log("Print dialog opening.");

  }

</script>
Try It Yourself

How It Works

The browser fires beforeprint on window when the print UI opens. The inline attribute on body wires up the same handler.

Dynamic Values with JavaScript

Attach the handler with addEventListener:

dynamic-onbeforeprint.html
<script>

  window.addEventListener("beforeprint", () => {

    console.log("Dynamic logic before print dialog.");

  });



  // Or property form:

  window.onbeforeprint = function () { /* … */ };

</script>
Try It Yourself

How It Works

Register the listener once at page load. Every time the user opens the print dialog, beforeprint runs your preparation code before the print layout is rendered.

Example — Pair with afterprint

Prepare print styles before printing, then restore on close:

before-after-print.html
window.addEventListener("beforeprint", () => {

  document.body.classList.add("print-mode");

});



window.addEventListener("afterprint", () => {

  document.body.classList.remove("print-mode");

});
Try It Yourself

How It Works

beforeprint prepares the page; afterprint undoes temporary changes so the screen view returns to normal.

♿ Accessibility

  • Do not hide essential content from print — Changes in beforeprint should improve the printed page, not remove information users need on paper.
  • Print styles in CSS — Use @media print so content remains readable on paper without relying only on JS.
  • Avoid alert() — Replace demo alerts with status text; alerts trap focus and delay the print dialog.
  • Keep handlers fast — Slow beforeprint code can make the print dialog feel sluggish.
  • Always pair with afterprint — Temporary DOM or class changes should be restored when the dialog closes.

🧠 How onbeforeprint Works

1

User opens print

window.print() or browser menu.

Trigger
2

beforeprint fires

Handler runs first.

onbeforeprint
3

Print dialog shown

User prints or cancels.

Dialog
=

Page prepared

Print layout ready.

Browser Support

The beforeprint event and onbeforeprint handler are supported in Chrome 63+, Firefox 6+, Safari 13+, and Edge 79+. Older browsers may not fire these events; rely on @media print CSS as a baseline.

DOM Events · Fully supported

Universal onbeforeprint support

All major browsers fire the underlying event and honor the onbeforeprint handler attribute.

98% Browser support
Google Chrome 63+
Full support
Mozilla Firefox 6+
Full support
Apple Safari 13+
Full support
Microsoft Edge 79+
Full support
Internet Explorer IE 9+ supported
Full support
Opera Fully supported
Full support
onbeforeprint attribute 98% supported

Bottom line: Widely supported in modern browsers. Test print preparation and cancel flows in your target browsers.

💡 Best Practices

✅ Do

  • Use addEventListener on window — Clearer than inline onbeforeprint.
  • Pair with afterprint — Every prepare step should have a matching restore step.
  • Prefer @media print CSS — Use JS events only when CSS alone is insufficient.
  • Keep handlers fast — Avoid heavy work blocking the UI before the dialog opens.
  • Hide screen-only chrome — Nav bars and toolbars are common beforeprint targets.

❌ Don’t

  • Do not assume print success — beforeprint runs even if the user later cancels.

Conclusion

The onbeforeprint attribute runs JavaScript when the print dialog opens and the beforeprint event fires on window. Use it to prepare the page for printing before the layout is rendered.

Pair it with onafterprint, prefer addEventListener("beforeprint", …), and remember the event means “print flow starting,” not “print succeeded.”

Key Takeaways

Knowledge Unlocked

Five truths every developer should know about onbeforeprint

Bookmark these before wiring your next event handler.

5
Core concepts
🌐 02

window target

Not img/form.

Scope
🔄 03

Prepare UI

Before afterprint.

Pattern
📝 04

addEventListener

Preferred.

Modern
05

Not success proof

Opens early.

Note

❓ Frequently Asked Questions

It runs JavaScript when the beforeprint event fires — when the print dialog opens or print preview starts.
No. It fires when the print dialog opens, before the user prints or cancels. Use it to prepare layout, not to confirm paper output.
On window via addEventListener("beforeprint", …). Inline onbeforeprint on body also works.
onbeforeprint runs when the dialog opens (prepare). onafterprint runs when it closes (restore).
Yes. @media print { … } handles most print styling without JavaScript. Use beforeprint when you need script-driven preparation.
Call window.print() or use the browser Print command. beforeprint fires as soon as the print UI opens.

Prepare pages for printing

Practice inline onbeforeprint, addEventListener, and afterprint pairing in the Try It editor.

Try onbeforeprint demo →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful