Reputation: 21
I'm trying to create a javascript function where content is switched out before window.print
is initiated, then switches the content back after the page has been sent to the printer. I have tried using document.body.onfocus
, but some print methods (such as printing to PDF) return focus to body
before the page is actually printed, thus replacing the intended content with the original content.
Here is what I have at the moment, and where the listener I think I would need would fit in:
function printNewContent() {
var title = document.getElementById("OriginalTitle");
var secondtext = document.getElementById("TextBlock2");
var copy = document.getElementById("StandardCopy");
var origtitle = title.innerHTML;
var origcopy = copy.innerHTML;
var newcopy = document.getElementById("NewCopy").innerHTML;
title.innerHTML = "New Title";
copy.innerHTML = newcopy;
secondtext.className = "displayNone";
window.print();
//Listen for page to be sent to the printer
title.innerHTML = origtitle;
copy.innerHTML = origcopy;
secondtext.className = "PrintOnly SecondTxt";
}
I would use delays in conjunction with the onfocus
approach, but that's not a foolproof method, and I'm looking for something as stable and consistent as possible. Any suggestions would be greatly appreciated. Thanks!
Upvotes: 2
Views: 292
Reputation: 55220
IE already have onafterprint
from earlier days.
With HTML5, onafterprint became an event for non-IE browsers too.
See MDC and W3C Specification on onafterprint
for details
Upvotes: 1
Reputation: 37516
An alternative approach would be to use a CSS media query to show/hide content on your site when it's being printed. This is a much better approach than trying to manipulate the DOM before printing, and trying to change it back.
For example, let's say you want your web page to show one element when it's viewed on the screen, but when it's printed, you want that to be hidden, and show something else. You'll need to render the HTML for both the screen version and printed version ahead of time.
Markup:
<div class="screen">
This is the stuff normal users will see.
</div>
<div class="print">
This is the stuff that will be printed.
</div>
CSS:
.print { display: none; }
@media print
{
.print { display: block; }
.screen { display: none; }
}
Upvotes: 3
Reputation: 7941
i think there is onafterprint
event but this works on only internet explorer.
http://forums.asp.net/p/969033/1217303.aspx
you should use the different styles for different screens with css:
Javascript Event Handler for Print
Upvotes: 0