Reputation: 152935
Is there any solution to disable Javascript style changes in print?
For instance, if I'm hiding something through Javascript but I want to include that hidden info in print.
I hid a div
using Javascript and I want to show that div
if Javascript is disabled. Now the problem is, because div
is hidden using Javascript it's also not showing when the page is printed.
Upvotes: 5
Views: 10173
Reputation: 143
I've found a workaround (at least, it works for me). In my instance i had a basic html page with some styling (screen.css & print.css) plus some javascript to progressively enhance the page with extra features, etc.
When it came time to print the page i realised that the js was affecting the layout (since i was doing some css styling via jquery).
What i ended up doing was this:
in "screen.css"
body {
background-color: #ccc; /* or whatever colour your designer chose; if it NEEDS to be white, simply change something else (e.g. background-image, font-size, etc.) */
}
in "print.css"
body {
background-color: #fff;
}
in "the-javascript-file.js"
$(document).ready(function()
{
if (isPrinting() == false)
{
init();
}
});
function isPrinting()
{
var isPrint = false;
/* I'm not 100% sure about the string literal check 'rgb(255, 255, 255)',
should do some testing here with other values || other attributes...
(font-size, color, line-height, other attributes that will have the
greatest difference / variation between "screen" and "print" styles)
*/
if ($('body').css('background-color') == 'rgb(255, 255, 255)')
{
isPrint = true;
}
return isPrint;
}
function init()
{
// All sorts of awesome goes here
}
And that was it! It worked!
Here's an overview of what's happening:
Hope this helps someone out there :)
Upvotes: 3
Reputation: 944529
The use of !important
has already been mentioned, but it is a blunt instrument and things get very complicated once you start needing to override things which are already !important
.
One of the great benefits of CSS is that it allows you to separate style from structure. Instead of using JS to manipulate the style of an element, use it to manipulate the structure. For example, by manipulating the className
property.
Your screen media stylesheet can then hide the element, while leaving it visible for the print media stylesheet.
This has the additional benefit that you don't need to think about having to override these styles as they won't apply in the first place (for print).
Upvotes: 2
Reputation: 344783
Use a print stylesheet, along with !important
statements to force the element to be visible for printing.
<link rel="stylesheet" href="print.css" type="text/css" media="print" />
CSS:
#myDiv { display: block!important; }
Upvotes: 5