views:

159

answers:

3

The contents of the following div is derived dynamically: i.e a table is added dynamically to this div with some button.

My question is how to print the content of this div(window.print) and not other things in the page

<div id="newdiv" name="newdiv"></div>

Thanks.

+7  A: 

Two ideas:

  • Introduce a print stylesheet

     <link rel="stylesheet" href="print.css" type="text/css" media="print"  />
    

    that will give every element display: none except for newdiv:

     * { display: none } /* This should hide all elements */
     div#newdiv { display: block } /* This should make newdiv visible again */
    

    I can't test this right now but I can't see why this wouldn't work.

  • Copy the contents of the div into a newly created iframe element using JavaScript and print that.

    Lots of obstacles on the road that way, though. I'd try using CSS first.

Pekka
cant we do something like this in jquery$('#newdiv').val()and use window.print
Hulk
You could walk through all elements in jQuery, make them all invisible except for newdiv, and then invoke `window.print()` I suppose. Would have the same effect as the style sheet, with the difference that the style sheet works with JS disabled as well. I don't really see an advantage there. As far as I know, you can't send chunks of HTML to window.print().
Pekka
+1. Stylesheets can be `disabled` and enabled whenever you need them too.
Andy E
+1. One can use a `.toPrint` class in the printing css, and use JS to tag the target div with that class.
ANeves
A: 

Your best bet is to create a media-specific style sheet.

http://www.alistapart.com/articles/goingtoprint/

digitaldreamer
+3  A: 

Clever thinking Pekka, but it doesn't work quite like that, after using a global display:none you would have to redisplay every single element that needs to be displayed, including all parent elements. Best way would be to hide all the elements that should not be printed, good news is that you only need to hide the parent element and everything in it will be hidden.

There is by the way no need for an extra style sheet, a block in an existing sheet can be used (it must be placed at the end of the last sheet):

@media print{
    .noprint{
        display:none;
    }
}

Now a block can be hidden from printing simply by giving its container the noprint class.

eBusiness
@eBusiness you make an excellent point if the document is very complex. +1.
Pekka