View video tutorial

HTML onafterprint Attr

HTML

The HTML onafterprint event attribute executes a script after a document begins printing or after the print dialog box closes.

Definition and Usage


➔ This attribute is usually associated with the window or document element.

➔ The primary purpose of onafterprint is to handle the actions required after the user completes or exits the print operation.

➔ The onafterprint attribute is often used in conjunction with the onbeforeprint attribute.

Example
    <body onafterprint="myFunction()">
        <!-- Page content goes here -->
    </body>

➔ Using JavaScript in DOM.

Example
    window.onafterprint = function() {
        // Code goes here to execute after printing or print dialog closure.
    };

➔ Using JavaScript addEventListener.

Example
window.addEventListener('afterprint', function() {
        // Code goes here to execute after printing or print dialog closure.
    });

Applies to

This attribute can be used on the following element.

Attribute Element
onafterprint <body>

➔ JavaScript addEventListener Example.

Example
<!DOCTYPE html>
<html>

<head>
    <title>addEventListener 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>addEventListener Event Example</h1>
    <button id="mybutton">Click</button>
    <script>
        let x = document.querySelector("#mybutton");
        x.addEventListener('click', handlerFunction);
        function handlerFunction() {
            alert("Hello from JavaScript!");
        }
    </script>
</body>

</html>

Click on the "copy" button and try this example in your project.