M. A. Cordeiro
M. A. Cordeiro

Reputation: 479

Media query print doesn't work by javascript command

I'm building a html report using media query print. Up to this point everything was working well, until I added a "Print" button to the page that performs the JavaScript command "window.print()". By using the shortcut (Ctrl + P) my web browser shows the print preview according to the media print, however, when I click on the "Print" button, the media query rules is been ignored.

Does anyone now how to fix it?

@media print {

  @page { 
    size: A4; 
    margin: 1cm
  }

  body * {
    visibility: hidden;
  }

  .printArea, .printArea * {
    visibility: visible;
  }

  .spacePrint{
    border: 1px solid #ccc;
  }

  .printArea {
    margin-top :0;
    position: fixed;
    left: 0;
    top: 0px;
  }
}

Upvotes: 4

Views: 2420

Answers (2)

samyok nepal
samyok nepal

Reputation: 557

This can be fixed by waiting for the event queue to clear before calling window.print(). This code worked for me:

setTimeout(() => window.print(), 0);

Upvotes: 0

Gopikrishna S
Gopikrishna S

Reputation: 2441

It does work ... here's a sample.

Tested in Chrome, IE11, and Edge.

function doPrint() {

  window.print();

}
@media print {
  @page {
    size: A4;
    margin: 5cm;
  }
  body * {
    display: none;
  }
  body h1 {
    display: block;
  }
}
<body>
  <h1>Print Hello World!</h1>
  <div>You cannot print me!</div>
  <button onclick="doPrint()">Print Me!</button>
</body>

Upvotes: 3

Related Questions