HTML onbeforeprint Event Attribute

Description

The onbeforeprint HTML event attribute is used to specify a JavaScript function that will be executed when a document is about to be printed. This function can be used to perform any necessary tasks before printing, such as hiding or showing certain elements, or modifying the document's CSS.

The onbeforeprint attribute is typically used in conjunction with the onafterprint attribute, which specifies a JavaScript function that will be executed after a document has been printed. This can be used to perform any necessary cleanup tasks, such as restoring the document to its original state.

Here is an example of how to use the onbeforeprint attribute:

<body onbeforeprint="myBeforePrintFunction()">
  ...
</body>

The myBeforePrintFunction() function will be executed when the document is about to be printed. You can use this function to perform any necessary tasks before printing, such as hiding or showing certain elements, or modifying the document's CSS.

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

function myBeforePrintFunction() {
  // Hide the header element
  document.querySelector('header').style.display = 'none';

  // Change the font size of the body element
  document.querySelector('body').style.fontSize = '12px';
}

When the user clicks on the print button, the myBeforePrintFunction() function will be executed before the print dialog box appears. This will hide the header element and change the font size of the body element before the document is printed.

Syntax

<element onbeforeprint="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>onbeforeprint event</title>
</head>
<body onbeforeprint="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 onbeforeprint event is supported only in Internet Explorer and Firefox.</p>
<script>
function test() {
alert("EXAMPLE: You are about to print this document!");
}
</script>
</body>
</html>

Browser Support

The following table will show you the current browser support for the HTML onbeforeprint 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