How to write a print.css equivalent in JavaScript

A common practice in the field of Web Development is to add a print.css file. This file breaks down your existing web page and enables you to view a printable page. For anyone building an informative web site without anything too complicated, there is a nice JavaScript alternative that can do essentially the same thing. This may be done in the form of a button, a link, or a new browser window, among others. While often frowned upon, JavaScript is an extremely powerful language and can be used to do some amazing things, and this is just one of them.

Lets use a photo like this as an example, and pretend it has a different colored background:

Image

Now we want it to have a white background, and be nicely formatted for printing, like so:

Image

The following JavaScript code will do the trick:

write(document.getElementById(“content”).innerHTML)

What this code does is take any text, images, or links within a div named content, and overwrite it as the new content of the web page for the client. It also removes all CSS from the page automatically and formats it in a way that is nice for printing.

The following is another way in which to implement this technique:

write(document.getElementsByTagName(“body”)[0].innerHTML)

This is a nice way in which to grab all of the HTML content on the page, rather than just the main content area. I tried doing this with the html tag and for some reason it didn’t seem to work. The [0] is required in this example because JavaScript stores the data into an array. This is in case multiple instances of the same element exist within a single page.

Lastly, these are some ways in which to use the code on your site:

<button onClick=’write(document.getElementById(“content”).innerHTML)’>View Printable Version</button> 

<a href=” onClick=’write(document.getElementById(“content”).innerHTML)’>View Printable Version</a> 

That’s it! With these examples you have a way in which to convert your page into a printable version. The user can then view the page and print it off. There are also ways in which to modify CSS attributes with JavaScript in case you’d like to remove the bullets from an unordered list, or the border from a fieldset in a form. I will leave it up to you to learn that technique on your own time.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: