views:

1117

answers:

4

I'm trying to dynamically hide certain DIV's when a print (or print preview) occurs from the browser.

I can easily differentiate statically by having two style sheets, one for normal and one for print media:

But I need to go one step further and hide some elements dynamically when the print style sheet becomes active during a print based upon certain criteria

One way to easily solve it would be to handle a DOM event for handling print / printview, then I could just use jQuery to change the display:none on the classes that need to be hidden, but I can't find a DOM print event!!

Anyone know what the solution is?

+1  A: 

There's an onbeforeprint event in IE. It doesn't appear to be supported by other major browsers. (I tested Firefox 3.0.3 and Safari 3.1.2.)

Patrick McElhaney
+4  A: 

Not all browsers allow you to capture the print event. I've seen this tackled by adding a 'print this page' link and then using that click event to accomplish what you need.

derby
+3  A: 

Just tag those DIVs with a class that's hidden on the print stylesheet:

HTML

<div id='div19' class='noprint'>
  ...
</div>

print.css

.noprint {
  display: none;
}

If you don't know in advance which elements you need to hide, you can use javascript to set the class for the given objects:

Javascript

document.getElementById('div19').className='noprint';
Marcus Downing
+4  A: 

I don't think you need a print event. All you need to do is adjust your @media print styles based on your Javascript(?) criteria. When the user attempts to print the page, the @media print style will apply and your styles will be in effect:

<html>
<head>
<style id="styles" type="text/css">
@media print { .noprint { display:none; } }
</style>
<script type="text/javascript">
var x = Math.random();

if (x > .5) {
    var style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = '@media print { .maybe_noprint { display:none; } }';
    document.getElementsByTagName('head')[0].appendChild(style);
}
</script>
</head>
<body>
<div class="noprint">This will never print.</div>
<span class="maybe_noprint">This may print depending on the value of x.</span>
</body>
</html>

If you are using server-side criteria to determine what prints, then just have server-side code spit out @media print to decorate the classes as necessary. Also, you may want to consider modifying an existing class that's already inside @media print, or building up the new CSS using something other than innerHTML, which I'll admit smells awful to me, but seems to work in Opera 9.6, Safari for Windows 3.1.2, IE 6 and Firefox 2.0.0.17 (I didn't test any other browsers).

Grant Wagner