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.
jQuery Code:$('#sudo). click(function(){ window. print(); return false; });
To print the content of div in JavaScript, first store the content of div in a JavaScript variable and then the print button is clicked. The contents of the HTML div element to be extracted.
One of those solutions are: I can keep this HTML content in a div and make it display: to print, but display: none to screen. All other elements on the webpage can be made to display: none for print and display: for the screen. And then call to print.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With