JavaScript afterprint
Event: Document Print Completion
The JavaScript afterprint
event is a powerful tool for web developers, providing a way to execute code after a user has printed a document. This event is particularly useful for performing cleanup operations, logging print activities, or modifying the user interface post-print. Unlike the beforeprint
event, which is triggered before the print dialog appears, afterprint
ensures your code runs after the print process is fully completed.
Understanding the afterprint
Event
The afterprint
event is triggered when a user has finished printing a web page, either by sending it to a physical printer or saving it as a PDF or another digital format. This event offers a reliable method to handle any necessary actions once the print job has concluded. It allows you to handle cases like:
- Logging: Record when a document was printed.
- UI Cleanup: Restore elements that were modified for printing.
- Analytics: Track print usage for reporting.
- Post-Print Operations: Trigger actions dependent on the successful completion of printing.
Syntax
The afterprint
event can be used either directly as an HTML attribute or through JavaScript using addEventListener
.
HTML Attribute:
<body onafterprint="yourFunction()">
<!-- Content Here -->
</body>
JavaScript Event Listener:
window.addEventListener('afterprint', yourFunction);
In both cases, yourFunction
is the JavaScript function that will be executed when the afterprint
event occurs.
Event Object
The afterprint
event does not provide a specific event object with properties like the MouseEvent
or KeyboardEvent
. It is simply a notification that the printing process is complete. Hence, the callback function you define doesn’t typically need event argument.
Practical Examples
Let’s explore some practical examples to demonstrate how to use the afterprint
event effectively.
Basic Usage: Displaying an Alert After Printing
This example shows a simple alert message that appears after a document has been printed.
<!DOCTYPE html>
<html>
<head>
<title>afterprint Basic Example</title>
</head>
<body onafterprint="afterPrintHandler()">
<h1>Print This Page</h1>
<p>Click the print button to see the afterprint alert.</p>
<button onclick="window.print()">Print</button>
<script>
function afterPrintHandler() {
alert('Document printing completed!');
}
</script>
</body>
</html>
Output:
After the user clicks the “Print” button and completes the print action, an alert box will appear with the message “Document printing completed!”.
Logging Print Activity
This example demonstrates how to log when a document was printed.
<!DOCTYPE html>
<html>
<head>
<title>afterprint Logging Example</title>
</head>
<body>
<h1>Print This Page</h1>
<p>Click the print button to log the print event.</p>
<button onclick="window.print()">Print</button>
<div id="logArea"></div>
<script>
function logPrintActivity() {
const logElement = document.getElementById("logArea");
const now = new Date();
const logEntry = `Document printed at: ${now.toLocaleTimeString()}`;
logElement.innerHTML += `<p>${logEntry}</p>`;
}
window.addEventListener("afterprint", logPrintActivity);
</script>
</body>
</html>
Output:
After a user completes printing, a log entry will be displayed within the logArea
div, showing the time at which the print occurred.
UI Cleanup Post-Print
This example shows how to restore the UI after a print, like a modal or some temporary change that was made for printing.
<!DOCTYPE html>
<html>
<head>
<title>afterprint UI Cleanup</title>
<style>
.print-friendly { display: none; }
</style>
</head>
<body>
<h1>Print This Page</h1>
<button onclick="prepareForPrint()">Print Preview</button>
<div id="modal" style="display: none; border: 1px solid black; padding: 20px;">
<p>This content will be visible for printing.</p>
<p class="print-friendly">Additional details only for printing.</p>
</div>
<button onclick="window.print()">Print</button>
<script>
let isModalOpen = false;
function prepareForPrint() {
const modalElement = document.getElementById("modal");
isModalOpen = true;
modalElement.style.display = 'block';
}
function restoreUI() {
if(isModalOpen){
const modalElement = document.getElementById("modal");
modalElement.style.display = 'none';
isModalOpen = false;
}
}
window.addEventListener("afterprint", restoreUI);
</script>
</body>
</html>
Output:
Initially, the modal
div is hidden. When the “Print Preview” button is clicked, the modal is displayed, and the print-friendly
elements become visible for printing. Upon printing, the modal disappears and the UI is back to the original state.
Using afterprint
with beforeprint
Event
The afterprint
event can also be used to reset the effects of the beforeprint
event. Consider an example where we hide some elements with beforeprint
and display them back using afterprint
:
<!DOCTYPE html>
<html>
<head>
<title>beforeprint and afterprint</title>
</head>
<body>
<h1>Print This Page</h1>
<p id="hide-para">This paragraph will be hidden during the print preview</p>
<button onclick="window.print()">Print</button>
<script>
function hideElement() {
const element = document.getElementById('hide-para');
element.style.display = 'none';
}
function showElement() {
const element = document.getElementById('hide-para');
element.style.display = 'block';
}
window.addEventListener("beforeprint", hideElement);
window.addEventListener("afterprint", showElement);
</script>
</body>
</html>
Output:
Before print, the paragraph element with hide-para
will be hidden, and after the document is printed, it will become visible again.
Browser Support
The afterprint
event is widely supported by modern browsers, but it is important to note that its behavior may vary slightly. Some browsers may not trigger the afterprint
event if the user cancels the print job, while most modern browsers will.
Browser | Support |
---|---|
Chrome | Yes |
Firefox | Yes |
Safari | Yes |
Edge | Yes |
Opera | Yes |
Note: Always test your implementations across different browsers to ensure consistent behavior. ๐งช
Best Practices
- Avoid Heavy Operations: Do not perform resource-intensive tasks within the
afterprint
event handler, as the user may have already closed the printing dialog or be waiting to interact with the page. - Test Thoroughly: Always test your code across different browsers and operating systems to identify any unexpected behavior.
- User Experience: Keep in mind that the user may not always complete a print job, and your code should handle that possibility gracefully.
Conclusion
The afterprint
event in JavaScript provides a valuable mechanism for performing actions once a print job has been completed. Whether you’re logging activity, restoring the UI, or triggering post-print operations, understanding this event will allow you to create a better user experience on your web pages. Always keep in mind that printing can be a complex process that can vary between browsers and systems, thus it is important to plan your implementation accordingly.