Reputation: 32390
I am working on an HTML page (no server-side scripting) web page with JavaScript.
My page displays a cascading menu of articles to the user. When the user selects an article, the article is displayed to the user.
I want to program my page so that when the user clicks "Print", only the title and article appear to the user.
I did the following:
1) I wrapped all sections of my page within DIVs with class='nonPrinterContainer'
. I created a blank DIV with class='printerContainer'
. I added some jQuery JavaScript that does the following whenever a new article is displayed:
1) Set the inner HTML of the printerContainer
DIV to an empty string.
2) Copy the HTML for the selected title and article to the inner HTML of the printerContainer
DIV.
Finally, I added a CSS stylesheet to the page:
<link type='text/css' rel='Stylesheet' media='print' href="styles/print.css" />
.nonPrinterContainer { display:none; }
.printerContainer { display: block; }
At first, this seemed to work great. I would open the page, click on an article, click print, and only the article title and article would print. However, to my dismay, I discovered that when the user clicks on one article and then another in a way that makes the menu disappear and then reappear (part of my page logic), the menu then becomes part of the page that prints.
I opened up the page in FireBug and reproduced the error. When I browse the JavaScript-modified markup code in FireBug, I see that as I expected, only the article title and text appear in the .printerContainer
.
How can it be that if everything else (including the menu) can be wrapped inside a DIV with display:none
in the print stylesheet, and yet the menu still prints sometimes. I also tried adding #menu { display:none; }
to my print stylesheet to no avail.
I think that this may have something to do with the way I use jQuery.show()
to display the menu. But to repeat, this bug only appears when I click on an option that makes the menu disappear and then reappear.
How can I better asset control over what part of my JavaScript-driven page prints?
Upvotes: 0
Views: 528
Reputation: 32390
Thanks for the answer, @Diodeus. I think I may have found a more suitable solution for my particular issue.
On my page, I had the menu in a div with class nonPrinterContainer
. However, I repeatedly called jQuery.show()
and jQuery.hide()
on the menu in my script. This seemed to somehow override my print stylesheet.
The solution I have discovered is to nest the menu inside a seperate div with class nonPrinterContainer
like so:
<div class='nonPrinterContainer'>
<div id='menu'></div>
</div>
instead of
<div class='nonPrinterContainer' id='menu'>
</div>
Upvotes: 0
Reputation: 114377
One technique I've used to to have a hidden Iframe. Copy the content you want to the Iframe, then call window.print()
from the iframe instead.
Upvotes: 1