Printing Web Page Contents

For the last calculator I put online I wanted to add a print button to make it easy to, well, print. Sure, I could just print the entire web page. But that’s a lot of extra noise. What I wanted was a button that would print just the output from the calculator and nothing else.

Like most things programming related StackOverflow pointed me towards a solution.

The idea is that a bit of JavaScript creates a pop up window, puts the contents of the div element that I want to print in that pop up, and then prints it.

function printElement (elem, head, foot){
    head = head || '<h1>' + document.title + '</h1>';
    foot = foot || ''; 
    foot += '<p>' + document.getElementById('credits').innerHTML + '</p>'; 
    var mywindow ='', 'PRINT', 'height=400,width=600');

    mywindow.document.write('<html><head><title>' + document.title + '</title>');
    mywindow.document.write('<style type="text/css">html { font-family: sans-serif; -webkit-print-color-adjust: exact; } td { text-align:right; border-spacing:0; } tr:nth-child(even) {background: #eee;} </style>'); 
    mywindow.document.write('</head><body >');

    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10*/


    return true;

It’s a bit modified from the StackOverflow version. I added parameters for the head and foot that print above and below the output.

I also added a bit of CSS to the head section so that it matches this site and also displays the zebra striping on the table.

Using It

The it was just a matter of hooking into the click event on a button. I’m using jQuery, but this would work pretty much the same however you’re attaching events.

jQuery('#print').click(function() {
    printElement('print-contents', '<h1>Partial Credit Calculator</h1>', ''); 
    return false; 

The element I want to print has an id of print-contents so that’s the first parameter. The second is what I wanted for the heading. And I didn’t want anything in the footer.

If you’d like to see it in action you can use the Partial Credit Calculator. You will have to type in some grades and click Calculate before the print buttons shows up though.


Next step I need to go back and add this little snippet to all the calculators on my site to make them easier to print as well. Newsletter

Want to stay in touch and keep up to date with the latest posts @

Leave a Reply

Your email address will not be published. Required fields are marked *