views:

24

answers:

2

I have this print style sheet switcher i created a long time ago and know it wont work for some reason, its suppose to switch to a print style sheet when the link is clicked and display the print dialog box.

But know it will only display the dialog box in FireFox and not in any other browser and will not display the print style sheet at all. Can some one help me fix these problems as its been a while since I played around with PHP.

Here is the PHP code.

<!-- Print Script -->
<?php if (isset($_GET['css']) && $_GET['css'] == 'print') { ?>
<meta name="robots" content="noindex" />
<link rel="stylesheet" type="text/css" href="http://localhost/styles/print.css" media="print" />
<script type="text/javascript">
//<![CDATA[
onload = print;
//]]>
</script> 
<?php } else { ?>
<link rel="stylesheet" type="text/css" href="http://localhost/styles/style.css" media="screen" />
<?php } ?>
<!-- End Print Script -->

And here is the link you click to change the style sheet.

<a href="<?php echo $_SERVER['PHP_SELF']; ?>?css=print" id="print-page" title="Print Link">Print This Page</a>
A: 

Change this:

onload = print;

To this:

if(window.print())
  onload = window.print();
else
  onload = window.print;

If you wanted it in a ternary style

onload = (window.print()) ? window.print() : window.print;

This will allow the browser to check and see if it "sees" the window.print function. If it can't (like in the case of Opera), then use the other version.

Also, be careful about cleaning the $_SERVER["PHP_SELF"] value.

random
now it wont work in opera. and the style sheet wont't display
jab
Have edited for the case of Opera and other browsers who call the `print` function differently.
random
+1  A: 

If its not working in IE, try this:

window.onload = function(){ window.setTimeout('print()',100) };

This will delay the call just a bit to give IE time to process.

However....

I would just always list both stylesheets. Since style.css is set to media="screen", print.css will be the only stylesheet uses by the browser to format the printed page:

<link rel="stylesheet" type="text/css" href="http://localhost/styles/style.css" media="screen" />
<link rel="stylesheet" type="text/css" href="http://localhost/styles/print.css" media="print" />

And set up the print link like this:

<a href="#" id="print-page" title="Print Link" onclick="print(); return false">Print This Page</a>

It would save an unnecessary call to the server... and might avoid your problem altogether.

Doug Neiner