onbeforeprint

The onbeforeunload event activates a function before the page is unloaded, giving you the opportunity to warn users about unsaved changes or show a confirmation dialog when they try to navigate away or reload the page.

onbeforeprint Event

The onbeforeprint event fires before a print action occurs, providing an opportunity to adjust the content or styling for optimal print output.

Syntax

In HTML

index.html
<element onbeforeprint="myScript">

In JS

script.js
object.onbeforeprint = function(){myScript};

In JavaScript, the addEventListener() function is used.

script.js
object.addEventListener("beforeprint", myScript);

Example

::event-beforeprint ::
index.html
<!DOCTYPE html>
<html>
<body onbeforeprint="myFunction()">
<h1>HTML DOM Events</h1>
<h2>The beforeprint Event</h2>

<p>This example assigns an "onbeforeprint" event to the body element.</p>

<h3>Print this document!</h3>
<p><b>Tip</b>: The keyboard shortcut Ctrl+P prints a page.</p>

<script>
function myFunction() {
  alert("You are about to print this document!");
}
</script>

</body>
</html>

Values

  • <script>
    • A function or script that runs when the event is triggered.

Conclusion

The onbeforeprint event enables the execution of scripts before a page is printed, making it useful for adjusting layouts and other modifications. However, browser support is limited, mainly available in Internet Explorer and Firefox.