17

I am trying to hide some divs before the user prints this giant form, then display the divs again afterward. Thus I want to ignore the rest of the page, and only print the form itself.

Sure I could open a separate page when the user clicks the print button. The only thing is that the form is really long and it would be quite tedious to do that.


Edit: My previous question did not actually reflect what I was looking for. So I changed it to the current one.

Also thanks to all that suggested window.onbeforeprint and window.onafterprint. That was relevant to my edited question.

Marcel
  • 6,143
  • 15
  • 46
  • 52
  • Regarding your edit: does my answer not answer your question? I think the best way is add a style to your divs and then use @media in your style sheet or a link to print stylesheet. – Micky McQuade Oct 22 '08 at 00:51
  • It does. But I cannot accept two answers. – Marcel Oct 22 '08 at 01:05
  • Does this answer your question? [How do I hide an element when printing a web page?](https://stackoverflow.com/questions/355313/how-do-i-hide-an-element-when-printing-a-web-page) – Damjan Pavlica Oct 23 '20 at 14:49

4 Answers4

28

First, The Ok Way:

Take a look at window.onbeforeprint and window.onafterprint (the original question asked about how to do it programmatically I believe).

Now, the Better Way:

A better way to do this is with a style that is specifically for printing. In other words, your div might look like this:

<div class="someClass noPrint">My Info</div>

You would then have this in your stylesheet:

.someClass {font-family:arial;}
@media print {
    .noPrint { display: none; }
} 

Another Option

You could also put this in a separate stylesheet if you wanted so you don't have to mix styles:

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

Your screen stylesheet could have ".someClass" defined one way and then your print stylesheet could have it defined a completely different way.

Micky McQuade
  • 1,873
  • 1
  • 16
  • 21
17

IE supports onbeforeprint and onafterprint, but what you really want is a print stylesheet.

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

See also: this answer

Community
  • 1
  • 1
eyelidlessness
  • 62,413
  • 11
  • 90
  • 94
0

You may want to consider creating a style sheet specifically for printing using media="print"

David Schlosnagle
  • 4,263
  • 2
  • 23
  • 16
0

You should really implement this as CSS media=print styles. The media attribute of link element can be used to select to which media a stylesheet is applied. Check this article

spender
  • 117,338
  • 33
  • 229
  • 351