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
Browser Support
The following information will show you the current browser support for the HTML onbeforeprint event attribute. Hover over a browser icon to see the version that first introduced support for this HTML event attribute.
This event attribute is supported by all modern browsers.
Desktop
Tablets & Mobile
Last updated by CSSPortal on: 14th October 2023
