HTML onafterprint Event Attribute

If this site has been useful, we’d love your support! Running this site takes time and resources, and every small contribution helps us keep creating valuable content. Consider buying us a coffee to keep things going strong!

Description

The HTML onafterprint event attribute fires when a page has started printing, or if the print dialog box has been closed. It is a new event attribute in HTML5, and is supported by all major browsers except Internet Explorer and Edge.

The onafterprint event can be used to perform tasks such as:

  • Updating the UI to indicate that the print job is complete.
  • Hiding or disabling elements that are not needed for printing.
  • Performing cleanup operations, such as closing open files or releasing resources.

The onafterprint event is often used together with the onbeforeprint event attribute, which fires before the page starts printing. This allows developers to perform different tasks before and after the print job, such as hiding and showing different elements of the page.

Here is an example of how to use the onafterprint event attribute:

<body onafterprint="myAfterPrintFunction()">
  ...
</body>

The myAfterPrintFunction() function will be called when the page has started printing, or if the print dialog box has been closed.

Here is an example of a simple myAfterPrintFunction() function:

function myAfterPrintFunction() {
  // Update the UI to indicate that the print job is complete.
  document.getElementById("printStatus").innerHTML = "Print job complete!";
}

The onafterprint event can be used in a variety of ways to improve the user experience of printing web pages.

Syntax

<element onafterprint="script">

Values

  • scriptThe name of the script to use when the event has been triggered.

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>onafterprint event</title>
</head>
<body onafterprint="test()">
<h1>Try to print this document.</h1>
<p><b>Tip:</b>The keyboard shortcut Ctrl + P prints the page.</p>
<p><b>Note:</b>The onafterprint event is supported only in Internet Explorer and Firefox.</p>
<script>
function test() {
alert("EXAMPLE: This document will now be printed.");
}
</script>
</body>
</html>

Browser Support

The following table will show you the current browser support for the HTML onafterprint Event Attribute.

Desktop
Edge Chrome Firefox Opera Safari
YesYesYesYesYes
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
YesYesYesYesYesYes

Last updated by CSSPortal on: 14th October 2023