onafterprint

The onafterprint event activates when a page begins printing or when the print dialog is closed. It is supported by most major browsers, but not by Internet Explorer or Edge.

onafterprint event

The onafterprint event fires after the print dialog closes, regardless of whether the user completes or cancels the print. This event can be used to execute scripts once the printing process is finished. It can be added to the <body> or specific elements to track this event.

Syntax

In HTML

index.html
<element onafterprint="myScript">

In JS

script.js
object.onafterprint = function(){myScript};

In JavaScript, the addEventListener() function is used.

script.js
object.addEventListener("afterprint", myScript);

Example

::event-afterprint ::
index.html
<!DOCTYPE html>
<html>
<h1>HTML DOM Events</h1>
<h2>The afterprint Event</h2>

<body onafterprint="myFunction()">

<h3>Print this document!</h3>
<p><b>Tip</b>: The keyboard shortcut Ctrl+P prints a page.</p>

<script>
function myFunction() {
  alert("This document is now being printed");
}
</script>

</body>
</html>

Values

  • <script>
    • Specifies the script to execute when the event is triggered.
The onafterprint event is often used alongside onbeforeprint to handle print-related tasks effectively.

Conclusion

The onafterprint event enables scripts to run after the print dialog closes, making it useful for post-print tasks. While widely supported, it is not available in Internet Explorer or Edge.