javascriptjqueryhtmlprinting

Print a div content using Jquery


I want to print the content of a div using jQuery. This question is already asked in SO, but I can't find the correct (working) answer.

This is is my HTML:

<div id='printarea'>
    <p>This is a sample text for printing purpose.</p>
    <input type='button' id='btn' value='Print'>
</div>
<p>Do not print.</p>

Here I want to print the content of the div printarea.

I tried this:

$("#btn").click(function () {
    $("#printarea").print();
});

But it gives a console error when the button is clicked:

Uncaught TypeError: $(...).print is not a function

But when I am trying to print the entire page using

window.print();

it is working. But I only want to print the content of a particular div. I saw the answer $("#printarea").print(); in many places , but this is not working.


Solution

  • Some jQuery research has failed, so I moved to JavaScript (thanks for your suggestion Anders).

    And it is working well...

    HTML

    <div id='DivIdToPrint'>
        <p>This is a sample text for printing purpose.</p>
    </div>
    <p>Do not print.</p>
    <input type='button' id='btn' value='Print' onclick='printDiv();'>
    

    JavaScript

    function printDiv() 
    {
    
      var divToPrint=document.getElementById('DivIdToPrint');
    
      var newWin=window.open('','Print-Window');
    
      newWin.document.open();
    
      newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');
    
      newWin.document.close();
    
      setTimeout(function(){newWin.close();},10);
    
    }