The HTML onbeforeprint event attribute executes a script that is triggered before a document is printed.
Definition and Usage
➔ This event is triggered when a page is about to be printed, before the print dialog box is displayed.
➔ The onbeforeprint attribute is usually used in the <body> of an HTML document.
➔ The onafterprint attribute is often used in conjunction with the onbeforeprint attribute.
Example
<body onbeforeprint="myFunction()">
<!-- Page content goes here -->
</body>
Example
<!DOCTYPE html>
<html>
<head>
<title>onbeforeprint Event Example</title>
</head>
<body onbeforeprint="handlerFunction()">
<h1>onbeforeprint Event Example</h1>
<p>Document contents goes here..</p>
<script>
function handlerFunction() {
alert("Preparing page for printing...");
}
</script>
</body>
</html>
Applies to
This attribute can be used on the following element.
| Attribute | Element |
|---|---|
| onbeforeprint | <body> |
Example
<!DOCTYPE html>
<html>
<head>
<title>onbeforeprint Event Example</title>
<style>
button[id="mybutton"] {
width: 130px;
height: 40px;
border-radius: 5px;
background-color: #c1d1e1;
}
button[id="mybutton"]:hover {
background-color: #d1e1f1;
}
</style>
</head>
<body>
<h1>onbeforeprint Event Example</h1>
<p>Document contents goes here..</p>
<button id="mybutton">Click</button>
<script>
let x = document.querySelector("#mybutton");
x.addEventListener('click', handlerFunction);
function handlerFunction() {
alert("Preparing page for printing...");
}
</script>
</body>
</html>
Click on the "copy" button and try this example in your project.