Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Javascript to Change Display Styles (CSS) Without Affecting Print Styles

I have a web application that utilizes a separate print stylesheet to control how the page looks when it comes out of the printer. That was working wonderfully until I recently made some Javascript enhancements to the site. One of these enhancements allows the user to freeze the page header and navigation, as well as table headers. The Javascript behind this does some CSS trickery to freeze the elements on the screen. Unfortunately, applying position: fixed to my header (for example) causes it to print on every page, and this is not a desired effect. How can I use Javascript to tweak element styles on the client-side without affecting the print style?

@media print { #foo { color: blue; } }               /* Print definition */
@media screen { #foo { color: green; } }             /* Display definition */
document.getElementById('foo').style.color = 'red';  /* Overrides both! */
like image 259
Josh Stodola Avatar asked Jun 13 '11 19:06

Josh Stodola


1 Answers

Instead of changing properties on your elements with this:

document.getElementById('foo').style.color = 'red'; 

append a new <style> element, for example:

$('<style>@media screen { #foo { color: green; } }</style>').appendTo('head');

It would be better to concatenate all your required changes into one <style> element, if possible.

like image 165
thirtydot Avatar answered Oct 01 '22 13:10

thirtydot