Some times we would like to print some important content on the web page via printer. The JavaScript provide print () method to print contents of the current window. It implements print() function of the window object. The print() method opens print dialog box which allows to select printing options.
Syntax for Window.print
window.print ()
The print() method don’t have any parameters and doesn’t contain any return values.
JavaScript Print Example
<!DOCTYPE html> <html> <head> <script type="text/javascript"> function printpage() { window.print(); } </script> </head> <body> <form> <input type="button" value="Print" onclick="printpage()" /> </form> </body> </html>
- <script type=”text/javascript”> tag is used to define client side scripting which specifies MIME type of the script.
- window.print(); line specifies that it is used to print contents of the current window.
- <input type=”button” value=”Print” onclick=”printpage()” /> tag specifies where user can enter data and onclick attribute triggers when user clicks the mouse button once.
JavaScript Print Demo
- Save the file as print_page.html in your system.
- Just open the file in the browser, you will see the below picture in the browser. Note that the browser must support HTML specification.