Open a new page in a new window, print it and closed it
html, javascript, jquery
Solution
I figured it out, all works, I just had to make sure that my files I am printing leave in the same domain. I hope it can help others in need for such a thing, but any improvements on the code are welcome.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Open n Print</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type='text/javascript'>//<![CDATA[
$(function(){
function openPrintWindow(url, name, specs) {
var printWindow = window.open(url, name, specs);
var printAndClose = function () {
if (printWindow.document.readyState == 'complete') {
clearInterval(sched);
printWindow.print();
printWindow.close();
}
}
var sched = setInterval(printAndClose, 200);
};
jQuery(document).ready(function ($) {
$(".test").on("click", function (e) {
var myUrl = $(this).attr('data-url');
alert(myUrl);
e.preventDefault();
openPrintWindow(myUrl, "to_print", "width=700,height=400,_blank");
});
});
});//]]>
</script>
</head>
<body>
</br>
<a class="test" href="javascript:;" data-url= "doc.html">open print and close doc</a>
<br />
</body>
</html>
Problem
I still can't get this code to work, I am trying to use the "onClick" to swap the image once clicked, open this new page in a new window, print this new opened window and closed it. It opens the new page on the new window, but it prints a blank page and it cant close it, it seems that the focus is not been set somehow. Can any one help me on tis? Thanks! ``` <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="utf-8"> <title>Print it</title> <!--style type="text/css" media="print"> .noprint {visibility: hidden;} </style--> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> <script type="text/javascript"> $(function(){ $(".img-swap").live('click', function() { if ($(this).attr("class") == "img-swap") { this.src = this.src.replace("_off","_on"); } else { this.src = this.src.replace("_on","_off"); } $(this).toggleClass("on"); }); }); </script> <script type="text/javascript"> // <!-- Popup = { init : function () { $('a.action_print').bind('click', Popup.printIt); }, printIt : function () { var win = window.open('doc1.html','Printed','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=350,height=250'); if (win) { win.document.close(); win.focus(); win.print(); } return false; } } $(document).ready(function () { Popup.init(); }); // --> </script> </head> <body> <br> CLick to Print:<br><br> <p style=" padding: 125px 0; text-align: center;"> <a class="action_print" target="Printed"><img src="images/cam_off.png" class="img-swap" width="100" height="100" /></a> </p> </body> </html> ``` Thanks for looking!