Print page Section, Using javascript

So... you want to choose a section of a page to print, but don't want to use a separate stylesheet. And you don't want everything else on the page to print either, just that one section (maybe a recipe?)

Click the Print This Section button lower down the page, and see what comes up in your printer preview. It should be content including and below the rose image... this paragraph will not be included, as it is outside the scope of the print section, which is defined with a div that has the id of "printerdiv".

Test Image to see if this prints

The Javascript to go in the head section of the page

<script language="javascript" type="text/javascript">
function printerDiv(divID) {
//Get the HTML of div

var divElements = document.getElementById(divID).innerHTML;

//Get the HTML of whole page
var oldPage = document.body.innerHTML;

//Reset the pages HTML with divs HTML only

     document.body.innerHTML = 

     "<html><head><title></title></head><body>" + 
     divElements + "</body>";

//Print Page

//Restore orignal HTML
document.body.innerHTML = oldPage;


Now enclose the content you want to be printed with a div that has the id of printablediv

Below that div, add the print button,  

<input type="button" value="Print This Content" onclick="javascript:printerDiv('printablediv')" />

This content is below the printable div, and so should not show on your printer preview. I have not fully tested this on phones, and might find that jQuery will do a better job. But give this a try anyway, it might be (or might not be!) suitable for your needs. 

How This Works

If you don't understand how this works, then it doesn't matter, it won't stop it working. But for the curious, here is a description of what's happening.

First the button. When it is clicked that calls the function printablediv, and will do whatever that function is telling it to. So let's look at that.

Now the function. This first creates a variable called divElements and stores that in memory. This contains the content of the div we want to print later.  It creates another variable called oldPage and also stores that, this contains the HTML of the page. 

Next, the page is "wiped" and then rewritten with ONLY the basic html tags on it, so it has no content... no header, no footer, no navigation. It is basically just an HTML page shell. At the same time, it puts back our variable divElements, which you will recall contains the content that we want to be printed.

Voila, we now have an HTML page that contains ONLY the printable div content, and all we need now is add a button to print it. 

Once that part of the function has run, we restore the page as it was by running the oldPage variable.


Have your say about what you just read! Leave me a comment in the box below.