How to Create a Print Button with Javascript


In this article, we show how to create a print button with Javascript.

This button sends you to a print page so that you can print a document.

We do this through the print() function in Javascript. The print() function in javascript is a function which prints the content of a page.

If we combine the window object with the print function, the summation window.print(), it will print all of the contents on a window.

The Javascript print() function can be used in many practical ways on a web page. One way it can be used is to create a print button, which will then open up the Print Dialog Box. Another practical way it can be used is when redirecting a user to a printer-friendly page, the print() function can be tied to the onload event handler, so that a print dialog box opens automatically when the page loads.

All these examples will be shown below so that you can see them for yourself.

How to Create a Print Button

One practical way of using the print() function is to create a print button, such as a "Print This Page" Button.

Below is a button which prints all of the contents of a page:

When clicked, this will open up a Printer Dialog Box, where the user can select the number of copies, whether he wants all pages printed, etc.

This will print all contents of the page. Being that it prints all the contents of a page, it is best used on a printer-friendly page, where there are no unwanted elements to be printed, such as navigation bars, horizontal menus, ads, and other such elements, since again, it will print all the contents of the page.


The code to create this print button above is:

The HTML code is very simple. The button has an onclick event handler which calls the print() function when clicked. The window.print() statements means it will print all the contents of the window.

Automatically Print a Printer-friendly Page

Another very useful way to use the print() function is to automatically print a printer-friendly version of a page upon loading.

To do this, we place the following code to the <body> tag of the HTML document:

Thus, with this code, as soon as the page loads up, it calls the window.print()" function. This function opens the print dialog box, so that the user can print the page.

Click this line here to see an example of this here.

HTML Comment Box is loading comments...