
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add a Button to Print an HTML Page
To add a "PRINT" button on your HTML webpage which, when clicked, prints the whole webpage. This is a fairly simple functionality to add in a webpage and can be added using some HTML elements and plain JavaScript.
Therefore, let us discuss the approach for doing so.
Approach
Firstly, add a <input /> tag inside the HTML dom.
Assign its type attribute to "button" and give it some value.
Then assign an "onclick" handler to the input which will be handled using JavaScript.
The function that handles the click event of input tag will look like this ?
const handlePrint = () => { window.print(); }
The complete code for this approach will be ?
Example
<!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>
Advertisements