Thiago Soubra
Thiago Soubra

Reputation: 201

how to show the contents of a div only in the print file?

watch my code below. I have a content in a DIV that can be printed when the "PRINT" button is clicked. It's working fine, however I need this div (and its contents) to be hidden from the site page and only shown in the print file. Do you suggest anything to me?

    function printDiv(printThis) {
         var printContents = document.getElementById(printThis).innerHTML;
         var originalContents = document.body.innerHTML;
         document.body.innerHTML = printContents;
         window.print();
         document.body.innerHTML = originalContents;
    }
<div id="printThis">
    content
    </div>
    <input type="button" onclick="printDiv('printThis')" value="PRINT" />

Upvotes: 3

Views: 760

Answers (3)

Eddie
Eddie

Reputation: 26854

You can use css @media print

This will hide all body elements and show only the div #printThis and all its children.

@media print {
    body * {
        visibility: hidden;
    }

    #printThis,  #printThis * {
        visibility: visible;
    }

    #printThis {
        width : 100%;
        height : auto;
        position: absolute;
        left: 0;
        top: 0;
    }
}

js (No need to modify/hide elements. CSS will handle it)

function printDiv( printThis ) {
    window.print();
}

HTML:

<div id="printThis">
    content
</div>
<input type="button" onclick="printDiv('printThis')" value="PRINT" />

Upvotes: 3

Kelechi Igbonekwu
Kelechi Igbonekwu

Reputation: 91

its easy with bootstrap. first hide the div with the bootstrap class hidden-md hidden-sm hidden-lg hidden-xs them make it visible with the `visible-print class edit your html to

<div id="printThis" class="visible-print"> content </div> <input type="button" onclick="printDiv('printThis')" value="PRINT" />

Upvotes: 0

Mahdi Salah
Mahdi Salah

Reputation: 189

If you are using bootstrap you can just use a simple bootstrap class to hide or show a content in Print

<div class="hidden-print">content for non print</div>

<div class="visible-print">content for print only</div>

Upvotes: 0

Related Questions