Add a "Print" button on the HTML web page. When the button is clicked, the entire web page will be printed. This is a fairly simple feature to add to a web page and can be added using a few HTML elements and pure JavaScript.
So let's discuss ways to do this.
First, add the tag in the HTML dom.
Assign its type attribute to "button" and give it some value.
Then assign an "onclick" handler to the input that will be handled using JavaScript.
The function that handles the input tag click event is as follows -
const handlePrint = () => { window.print(); }
The complete code of this method is -
<!DOCTYPE html> <html lang="en-US"> <head> <title> Adding Print Button </title> </head> <body style="color: black;"> <h1>Hello World!</h1> <p>Welcome to my Website</p> <p> This website is built using plain JS and HTML. </p> <p> Okay Bye!!! </p> <input value='Print' type='button' onclick='handlePrint()' /> <script type="text/javascript"> const handlePrint = () => { var actContents = document.body.innerHTML; document.body.innerHTML = actContents; window.print(); } </script> </body> </html>
The above is the detailed content of How to add a button to print an HTML page?. For more information, please follow other related articles on the PHP Chinese website!