Open the Print Dialog with JavaScript

02/11/2022

Contents

In this article, you will learn how to open the print dialog with JavaScript.

The Window.print() method

To open the print dialog with JavaScript, use the Windows.print() method.

When printing a receipt on an EC site, you may have seen a function that displays a print dialog when you press a button.
You can achieve such a mechanism by using the Windows.print() method.

Also, in combination with CSS, it is possible to apply printing styles and set specific elements not to be printed.

The syntax is below.

window.print();

You can apply print styles by specifying print with @media (media queries).

@media print {
  /* do something */
}

To read an external css file for printing, write as follows.

<link rel="stylesheet" type="text/css" media="print" href="fileName">

Sample Code

Below is a sample code that uses the Window.print() method to display a print dialog.

HTML

<input type="button" value="print" class="noprint" onclick="window.print();"/>
<h1>Title</h1>
<p>texttexttexttexttexttexttexttext</p>

CSS

@media print {
  .noprint {
    display: none;
  }
  h1 {
    font-size: 42px;
    text-align: center;
  }
  p {
    font-size: 16px;
  }
}