Reputation: 41
I am working on a page, where the user may click a button and print some important information on the page.
Basic page structure is like:
<body>
<div id="printContent"></div>
<button>Print</button>
</body>
And the desired behavior is: when the page is being printed, only the contents inside "printContent" should be printed.
Before I used js code to do it by temporarily replacing the body with whatever is inside printContent, but this seems to slow down the page a bit when user gets out of the printing options pop-up. (The temporary content will occupy the whole page for a few seconds or some of the buttons and links become non-responsive for a few seconds.) So after referring to the second answer here:How do I print part of a rendered HTML page in JavaScript?
I used something like this:
@media print {
body * {
display:none;
}
body #printContent {
display:block;
}
}
But when printing, the printContent part is still invisible. Did I do anything wrong here? Thanks.
EDIT: My bad, it is not the second answer from the link, the second "Highest upvoted answer", namely the one with 15 upvotes.
Upvotes: 1
Views: 1012
Reputation: 167240
Okay, might be a lot of sub elements getting affected too. Try this:
@media print {
body * {
display:none;
}
body #printContent {
display:block;
}
body #printContent * {
display:initial;
}
}
Technically, you are resetting the display
for the inner contents too. Do you understand? When you give the global selector body *
, it also hides the inner components. So just unhiding the parent #printContent
will not be sufficient to unhide the children of it. To avoid all these hassles, you can do something like this if the #printContent
is a direct descendant of body
:
@media print {
body > * {
display:none;
}
body > #printContent {
display:block;
}
}
Upvotes: 1