Technology, Smartphones, Games


Print the content of a div using JavaScript

I just wanted to print the content of a div using Javascript. If you are also looking for the same, below code can help you to do that

function printDiv()
{

  var divToPrint=document.getElementById('DivIdToPrint');

  var newWin=window.open('','Print-Window','width=100,height=100');

  newWin.document.open();

  newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');

  newWin.document.close();

  setTimeout(function(){newWin.close();},10);

}

This JavaScript will open a new window with the content of the div, will print it and then will close that window. Last line, this is a must to set a timeout there, Otherwise in IE window will get closed before printing happens.

I struggled a bit when i faced this issue of printing a Div content and later find the solution. I think it will be helpful for those who are facing the same issue. If you found this article helpful, i will be happy to see a comment from you. Also there can be some better way to do this if you know it, please share it with us.