Blog Standard Stuff


How to Print Selective Sections of a Web Page using CSS and DOM Scripting

Posted in Tech, Web Standards, CSS, Scripting by Lloydi on the March 21st, 2006

This is an experiment to see if it’s possible to selectively print sections of a large document usings CSS print styles after the page has loaded without affecting the on-screen display.

Why might you use this? Well, the inspiration came from a page of interest rates from banking and savings products. Customers have often complained that the interest rates were split up on different sections - they wanted everything in one page. But what about those people who only want to print out the section that relates to them? One solution is to build the page using include files with separate printer-friendly pages that are linked to. This solution uses DOM scripting to dynamically apply print CSS styles depending on the link that has been clicked on - if the user clicks on ‘print this section’, all other sections are set to display none for print.

This technique could be use in

  • FAQs
  • Product information pages
  • … well, wherever you feel it has value

This has been tested and works in

  • Windows
    • Firefox 1.5
    • Netscape 6.2
    • Netscape 8
    • Opera 7.0
    • Opera 8.5
    • IE 6
  • Mac
    • Firefox 1.5
    • Camino 1.0
    • Opera 7.54

Notes:

The ‘print this section’ links are dynamically inserted for any section that is marked with the class name of section and are hidden using print CSS. No JavaScript, no see the links!

I have had to double up on the attribute setters in the script so that IE didn’t get upset. It’s not perfect, but it works and isn’t really nasty. No, honestly, it isn’t ;-)

el[i].setAttribute("className","section print");
el[i].setAttribute("class","section print");

View the Example Here »

And if you like what you see, why not digg it for me? Thanks

Copy the Code Here

Get the JavaScript here and the HTML here

66 Responses to 'How to Print Selective Sections of a Web Page using CSS and DOM Scripting'

Subscribe to comments with RSS or TrackBack to 'How to Print Selective Sections of a Web Page using CSS and DOM Scripting'.


  1. on March 21st, 2006 at 1:40 pm [link]

    […] Print Sections Of A Web Page with CSS and the DOM. […]

  2. kloche said,

    on March 21st, 2006 at 2:12 pm [link]

    You saved my life with this css/js “scriptage”

    I am currently doing a web development project for a university’s public relations office. This is not only a major solution to how can we allow different types of users with low and high browser interaction knowledge, print specific content like articles amongst orther content. But it’s also going to be integrated in some other future projects I have in the pipeline.

    Thank you so much

  3. henry said,

    on March 21st, 2006 at 3:05 pm [link]

    i’d rather simply would set

    #your_id_here { display:none; }

    the stuff i don’t want to be printed.

  4. Ian said,

    on March 21st, 2006 at 6:00 pm [link]

    henry, you are missing the point a little (and you are not the first). Sure, you can set printable and not printable areas at load time, but by default the whole page might be printable. Using this technique, only the section you want to be printed gets printed. Try this:

    - Click the ‘print this section’ link for section 3
    - Click the ‘print this section’ link for section 5
    - Then click the ‘print all’ link

    Notice that the page is not reloading - the print attributes are dynamically being changed. Now imagine a 30-page set of FAQs where you want to print just one section in that long page. Here’s a solution for just that eventuality. Do you see what I was striving for?

  5. John said,

    on March 21st, 2006 at 8:53 pm [link]

    I like your solution, but associating an id with each section seems like overkill to me. Would it work if you assigned the sections to the print links in the link creation function? This would look like link[k].section = section[k] in the script. (I’m pretty sure you can add arbitrary attributes to DOM elements, I did a quick test in Safari/Firefox/WinIE.) Then, when print button k was clicked, you just change section k to “print” and every other section to “noprint”, instead of divining the correct section from the link id.


  6. on March 21st, 2006 at 11:42 pm [link]

    Even better is the Scrapbook extension for Firefox (http://amb.vis.ne.jp/mozilla/scrapbook/) that lets you store, and later print, any section of any page, taking all CSS into consideration.


  7. on March 22nd, 2006 at 1:31 am [link]

    Cool.
    Alternatively, you could just select the text and select ‘Print selection’ if you have Hyperwords for Firefox installed.
    It’s a free download from http://www.hyperwords.net (or just click on my name above).

  8. Lloydi said,

    on March 22nd, 2006 at 1:58 am [link]

    @Richie and @Frode - these are both sensible suggestions but they are not what I was after because:

    1 - You need to be a Firefox User (still in the minority)
    2 - You need to be a fairly geeky Firefox user to be tinkering with and using these extensions on a regular basis (a minority of a minority group)

    (FWIW I include myself in those categories!)

    So from the point of view of a corporate website - which was the original inspiration for this idea (an interest rates page for multiple products) - that would be expecting too much of the user. With this JS/CSS solution, the user doesn’t need to have any special plug-ins installed.

    In short, the person using the web page does not need to be alpha geek material - they just get given some extra functionality that they otherwise would not, as long as their browser is capable of doing that particular JavaScript.

    @John - You may be right about the overkill woth ids. I suppose it could be added in dynamically, but I figured that if you have specific sections of a document (let’s use that long FAQ page as an example), then it’s beneficial to have id attributes in there anyway, as you can then link directly to sections on that page. I don’t think it’s a big overhead, really … but of course it depends on the length of the page!


  9. on March 22nd, 2006 at 3:12 am [link]

    […] Si voleu saber-ne més, tecnològicament parlant, podeu visitar: blog standar stuff, concretament el seu post sobre el tema, o bé anar directament a un pràctic exemple. Uncategorized […]

  10. Alastair said,

    on March 22nd, 2006 at 6:11 am [link]

    I use the Aardvark Firefox extension for this:

    http://www.karmatics.com/aardvark/

    It has several commands to isolate the section you are interested and remove the rest.

  11. Lloydi said,

    on March 22nd, 2006 at 6:29 am [link]

    Again Alastair, this is all well and good, but that means for selective printing the user has to have Firefox and that extension installed, and of course most don’t. Hence the script is there for all the browsers I’ve tested on (as listed above) without having the user need to go out and install anything specific or swap browsers.

  12. Nathan Logan said,

    on March 22nd, 2006 at 1:46 pm [link]

    This is great stuff. The “I use such and such extension” comments are ridiculous, and miss the point by so great a margin that I’m not even sure their authors read beyond the first 9 words of the article title.

    Excellent idea and nice implementation. Thanks!


  13. on March 22nd, 2006 at 4:34 pm [link]

    Whoops! I forgot to send you the class manager script today… Sorry dude!
    I’ve set myself a todo in iCal for tomorrow morning, so I (hopefully) won’t forget!

    The other suggestion I’d make is that, rather than setting the button’s id to “printall_” + el[i].id, why not just add a new property to the button as follows:

    newLink.printTarget = el[i];

    That would then allow you to replace togglePrintDisplay(e)’s opening few lines:

    var whatSection = this.id.split(”_”);
    whatSection = whatSection[1];
    var el = document.getElementsByTagName(”div”);

    with:

    if (!this.printTarget)
    {
    alert(”That link doesn’t work”); // Obviously you’d want a more descriptive error than this
    return;
    }
    var el = this.printTarget;

    Anywho, I’ll send you the other stuff tomorrow :)

  14. luxuryluke said,

    on March 23rd, 2006 at 6:55 am [link]

    Echoing nathan logan’s comments above!
    I make faq pages all the time, and this type of script would be ideal for this, ian. I DO use individual IDs in the questions and answers for many reasons. and sadly, one of the reasons your idea is so great, is that our “Corporate Browser” has been IE for a loooong time. Think there’s a chance of changing that soon? Doubt it. not this year anyway.
    Thanks so much, i’ll give it a shot on my next project.
    I’ll be putting it in here:
    http://employees.aero.org/parking/faq/

  15. luxuryluke said,

    on March 23rd, 2006 at 6:58 am [link]

    My only comment other comment would be:
    Why are there “#” links in the print links? This means the anchor hasn’t been hijacked according to JKeith’s ideas. Am I correct?

  16. Lloydi said,

    on March 23rd, 2006 at 7:28 am [link]

    Actually, you’re right - I’ve not ‘hijacked’ a link in the href by putting in a #. However, I have my reasons:

    1. There is no destination page to put there by default
    2. I am not concerned about having a fallback for non-JS able browsers (or those who have it disabled it), because if no JS present, the set-up script that writes the buttons/links in to the page will not run.

    Does that make sense?

    Given that it’s not a link as such, it’d probably be better to dynamically write in real input buttons or even an image - if JS is enabled, then I can hang an onclick or onkeypress event off it, regardless of the element.

    Any comment Jeremy?

  17. luxuryluke said,

    on March 23rd, 2006 at 9:39 am [link]

    That makes sense. I see what you mean.
    To make this more professional and robust, i would agree that these should not be ‘links’, then, in the hyperlink sense of the word.
    Nice work, again!

  18. Jeremy Keith said,

    on March 24th, 2006 at 8:12 am [link]

    It’s true that it’s a really bad idea to put href=”#” or href=”javascript:” in your markup. But, as always, there are exceptions and Ian has hit on one of them: if the link is being generated by JavaScript then effectively, you no longer have to deal with the “JavaScript off” fallback situation. So, there’s no problem generating an a element with href=”#” using JavaScript.

    However, luxuryluke is also correct when he says that these don’t necessarily need to be hyperlinks. Semantically, if there’s nothing useful in the href attribute, then maybe you shouldn’t be using an a element. You could generate a different element, say span, and attach event handlers to that (as well as throwing in a cursor:pointer in CSS to make it behave like a link).

    But really, we’re into angels-on-the-head-of-a-pin territory.

    BTW, Ian, you can do a simpler cross-browser setting of the class attribute using the DOM Level 0 syntax:

    el[i].className = “section print”;

    Normally, I much prefer using setAttribute but setting classes is an exception circumstance (because of the way IE handles attribute names that clash with reserved words in JavaScript… the “for” attribute is another example; in IE, you have to set “htmlFor”).

  19. adam said,

    on May 17th, 2006 at 1:27 pm [link]

    Hey there,

    I am really intrigued by this script… I am designing a site for childhood disability research and I haven’t been able to find anything except this that allows the user to just print one section off of a page…

    With that said, I am a little bit of a novice in terms of Javascript and CSS (i use mailny php and flash) and i am having trouble figuring out how to NOT print a certain section - For example, how would I get JUST section three to print without the title on the top included - in addition, I WOUDN’T want the title section at the top to be in a grey box with an option to print below it…

    Thanks so much,
    Adam

  20. vikas said,

    on June 2nd, 2006 at 3:01 am [link]

    In my application i have a link on press the link the image going to print but my problem is that i have to reduce the margin from left and right when any user giving the print command i have use the margin - left and margin - right in my css but it will not work. So please give me the solution for this if u have….

  21. Ramon Bispo said,

    on July 23rd, 2006 at 7:56 pm [link]

    Fantastic!

    Thanks for sharing.

  22. Andy said,

    on August 14th, 2006 at 12:38 pm [link]

    Hey, I’m also a big fan of this script — I’m really new to scripting in general; is there a way to modify this so it would use a print button jpg image instead of making a text box hyperlink?

  23. Tom said,

    on October 5th, 2006 at 12:18 am [link]

    Hello,
    I found this script and it looks like a perfect solution for my problem. I want to creat a “printcenter” function for larg pages with differet sections. Is it possible to give this script more than one section to print out? Maybe it’s possible to creat a form with checkboxes to say which sections should be print out?

    Thanks.

  24. Sari Ganesha said,

    on October 30th, 2006 at 10:16 pm [link]

    Thx … it works like a charm. ;)

  25. Walt said,

    on November 13th, 2006 at 3:44 pm [link]

    This script works great for printing an individual section, but oddly enough the print-the-whole-page link doesn’t work for me, and its mere presence seems to even break IE 6’s Print Preview function (File menu) without even using the link. I’m using ColdFusion and generating variable-length sections (each in a separate ) from a database, with some of the tables spanning more than 1 page. It appears that the first table prints okay, but after that it only prints the parts of subsequent tables that would slop over onto a 2nd printed page…. I know printing long tables is always dicey in IE, but I’m wondering: Is there a way to remove the Print-all functionality of the script without breaking the Print Section part? I don’t mind forcing my (ab)users to just use the IE Print button to print the whole page.

  26. GP said,

    on December 6th, 2006 at 12:45 am [link]

    I’m new to this print javascript, so where’s the html code of it or what code do you put into the body of page?

  27. achavan said,

    on December 12th, 2006 at 5:02 am [link]

    I want to print some reports which I’ll be accessing from other server using URL.
    I want to print these reports without displaying it to the user and only printer selection dialogue should apperar in this case and on clicking of print it must print those reports.
    Can you guide how to do this using Javascript?


  28. on December 20th, 2006 at 2:15 pm [link]

    I would avoid java if you can do the same thing with css or php. It will not be seo friendly which is important these days.

  29. Lloydi said,

    on December 20th, 2006 at 4:47 pm [link]

    Sacramento - it’s not Java, it’s JavaScript, and the JavaScript is only used to hide or show content that is, by default, visible on screen. So, there’s zero detrimental impact on SEO.

  30. Shameem said,

    on January 6th, 2007 at 3:37 am [link]

    I am facing following problem . Can anyone help me?
    I am having a screen where there is a table containing list of pdf files (each are hyperlink to open the files).
    Each row has a check box to select the documents.
    Once the user selects some files and clicks the Print Button, I had to print all the selected files to the default printer on the user’s PC.

    I am having a java application running on my server and serving the webpages to client.


  31. on January 6th, 2007 at 11:30 am [link]

    In that case that is a slick setup for printing. I’m assuming it would work for printing photos and color printing as well as b&w text printing.

  32. Lynne said,

    on January 19th, 2007 at 6:56 am [link]

    FYI - great script. But IE7 on XP isn’t rendering the buttons correctly - they come out as text links butted up against each other. Bit of a nit, but if you’re not aware of it…

  33. Jason said,

    on January 19th, 2007 at 1:12 pm [link]

    Does not appear to pull in the paragraph class in IE7. It shows the link and the link works. However it is not boxed in like it should be by the paragraph class.

  34. Jason said,

    on January 19th, 2007 at 8:38 pm [link]

    trying to implement on my website here: hvkayakpools.com/faqs.html. However the page cuts off some of the text, any suggestions?

  35. Jason said,

    on January 21st, 2007 at 9:05 pm [link]

    Corrected the second issue. Check out my blog post about this tool, still writing it though. Should be done by the end of the week: JFischWeb.com


  36. on January 21st, 2007 at 9:08 pm [link]

    […] Hello fellow web developers, another web design topic to tell you all about. Today’s blob topic is going to be a collage of setting up your website to print in a well formatted way using CSS of course! I will also discus how you can print individual sections of your site through another Java Script/ CSS gem I found on the internet (How to Print Selective Sections of a Website, a great solution for a hand coded faqs sheet. Sorry the blog does not have any cool pics or neat YouTube videos, but I will get there. So working on this thing while working my three jobs. So time permitting I will be expanding on this thing. […]


  37. on January 22nd, 2007 at 5:04 pm [link]

    It looks like firefox is working just fine though. I think the new 2.0 kills explorer, the phishing filter really slows it down.

  38. SDG said,

    on January 29th, 2007 at 3:15 pm [link]

    What if you want to print only text from the selected print_section div — and nothing else on the page, even elements that aren’t in a different print_section div?

    In the example above, the page header and intro text prints. I’m trying to suppress that as well.

    I did try putting the page header in a different div style that also suppresses printing. But that only works if each section is a discrete block unit — and layout constraints won’t allow me to create the page that way.

    I have my print_section divs in a page layout table cell (not the best design, but I’m stuck with it). I want to suppress the whole table and everything else on the page, but still print whichever print_section div is selected.

    I’m sure there’s a way to do it but I can’t figure it out.

  39. Jim said,

    on February 19th, 2007 at 9:54 am [link]

    This is a great idea. I wanted to implement it on a Vanilla forum. The problem I have is that on a Comments page where each div represents a Comment, the id is called CommentBody_xxx, when xxx is the actual Comment id number. Can the js be modified to handle this situation?
    Thank you.

  40. Jim said,

    on February 19th, 2007 at 8:45 pm [link]

    I have actually figured out what I had trouble with. However, I still have a problem, probably not understanding js. The print options appear fine at the end of each comment div. And when I click “print this section”, it does. However, it reformats the page. The first comment looks fine (except for a font change), but then each subsequent comment is indented further and further to the right. Why does this happen? And how can I fox it?
    Thank you for any help you can provide.

  41. Kevin said,

    on March 2nd, 2007 at 8:29 am [link]

    I’m not quite an expert with CSS or Javascript, but I have this script working wonderfully with a little tailoring to meet our needs. But I have a question, I can’t seem to find what is specifying the location that the links appear. My links are appearing at the end of each div section but I would like them to appear at the top instead. Could anyone tell me what I need to change? Thanks for any help and thanks Lloydi for this awesome script.

  42. Kevin said,

    on March 2nd, 2007 at 8:33 am [link]

    P.S. Also just noticed that they appear at the bottom of div sections in IE 7 but in Firefox and Netscape they appear at the top! Is there any way to regulate this?

  43. Kevin said,

    on March 2nd, 2007 at 8:45 am [link]

    Sorry, just a quick note…I realized that in Firefox and Netscape they are actually appearing at the top of the next div instead of inside the one they are supposed to be in.

  44. Ed said,

    on March 21st, 2007 at 12:22 pm [link]

    Lloydi,

    Great sample… I have had difficulty making it work in JS. (flash 8) though, Do you have a sample using JS. It would be gretaly appreciated.

    Thanks

  45. link ekle said,

    on March 23rd, 2007 at 8:29 am [link]

    In the example above, the page header and intro text prints. I’m trying to suppress that as well.

  46. atherix said,

    on March 28th, 2007 at 10:36 pm [link]

    Very Nice! The only thing I’ll change is getting rid of the onkeypress handler for the print buttons. I’m constantly using the arrow keys and alt+left arrow to navigate the web. When I click on a print button it gains the input focus, and the print dialog is popping up whenever I hit a key.

  47. John Rang said,

    on April 16th, 2007 at 2:27 am [link]

    Very cool! After going through many searches and all comments here –I think this is the best solution so far by Lloydi. I would try this out for my new contents based tourism guide site where visitors would need lots of information to be printed!
    Thanks


  48. on April 18th, 2007 at 3:56 pm [link]

    Very Nice and cool. I’ll change is the rid of the onkeypress handler for the print buttons. The first comment looks fine (except for a font change), but then each subsequent comment is indented further and further to the right. Why does this happen? And how can I fix it? Thnaks again.

  49. mcabarles said,

    on April 23rd, 2007 at 2:11 pm [link]

    Wanted to give you props for posting this - just exactly what the doctor ordered.
    Thanks!

  50. Sanjay said,

    on May 11th, 2007 at 10:43 pm [link]

    I would try this out for my new contents based tourism guide site where visitors would need lots of information to be printed!

  51. AcromE said,

    on July 3rd, 2007 at 5:26 am [link]

    Excellent.!!! Its work like charm..thank you

  52. Ignasi said,

    on July 12th, 2007 at 4:22 pm [link]

    Hello!

    I’ve readed your blog and I found this post, is great!

    I’m traying to add a “printer-friendly” a blogger Blog, do you know if it’s possible to add this script in blogger?

    I don’t know how to addapt a print´-friendly in bloger, I wish I could add this hack!!

    Thank you!

  53. chun said,

    on July 19th, 2007 at 12:28 pm [link]

    i tried example above using print_section.js and

    i printed the selected portion, but i also printed stuff above i specified stuff.

    How to only print selected portion?

    Thanks

  54. Dugu Miko said,

    on August 11th, 2007 at 10:21 am [link]

    Great script, work perfectly for what I needed it. But i would also like to know how to print only a small portion.
    Thanks, best regards,
    Dugu

  55. Kathir said,

    on August 28th, 2007 at 10:18 am [link]

    Hi all,
    Thanks for this useful script.
    But its not works for me…. may be i dont know how to use this.
    I have many table inside and outside a table and even tags. i have set the required table to be print section. its even get the CSS background. but when i print that section its print the whole body of page..
    If anyone know pls reply to me how to fix this.

    Regards,
    Kathir.B

  56. India said,

    on October 7th, 2007 at 4:12 pm [link]

    i tried example above using print_section.js and

    i printed the selected portion, but i also printed stuff above i specified stuff.

    How to only print selected portion?


  57. on November 2nd, 2007 at 2:16 pm [link]

    I would try this out for my new contents based tourism guide site where visitors would need lots of information to be printed!

  58. resimleri said,

    on November 2nd, 2007 at 2:18 pm [link]

    My only comment other comment would be:
    Why are there “#” links in the print links? This means the anchor hasn’t been hijacked according to JKeith’s ideas. Am I correct?


  59. on November 22nd, 2007 at 4:27 am [link]

    i try the script with pdfFactory (pdf), yes it works very well.. thanks for the script.

  60. Musto said,

    on November 25th, 2007 at 7:58 am [link]

    Dear Lloydi,

    Thank you for this script, it is great and it does save trees :) I noticed a user mentioned that in I.E7 you don’t get the seperate print boxes which it looks like the CSS creates via a DIV. I couldn’t see whether there has been an update to this?

    I’m doing an assignment for uni and I would really love for some help to get this working in I.E7, there must be something in I.E7 which doesn’t like the CSS.

    Please please if anyone has sorted this issue, can you let me know ASAP

    Kindest Regards

    Musto

  61. workerBee said,

    on November 27th, 2007 at 8:35 pm [link]

    css fix for the ie link bug:

    Add a style

    *.print_section a {add same styles as p.printbutton a }

    Tested it on 6.0 and it should be good to go on earlier v’s.

    Cheers


  62. on November 28th, 2007 at 5:08 am [link]

    a nice javascript function for the same purpose.
    http://www.designerkamal.com/jPrintArea/

  63. Deep said,

    on February 14th, 2008 at 9:54 pm [link]

    Why your code is not working on an ASP page ? The external javascript file is loading properly and the style attributes too !


  64. on March 3rd, 2008 at 2:25 pm [link]

    I want to print some reports which I’ll be accessing from other server using URL.
    I want to print these reports without displaying it to the user and only printer selection dialogue should apperar in this case and on clicking of print it must print those reports… ispanyolca tercüman

  65. idynn said,

    on April 11th, 2008 at 3:53 pm [link]

    I found this script and it looks like a perfect solution for my problem. Thank you.

  66. Andy Sharp said,

    on June 2nd, 2008 at 10:43 pm [link]

    Good stuff!

Leave a Reply