javascript - custom print function, print contents not showing on first event trigger -
to quick , precise please see fiddle.on first click on button has label of "print", new window open (print contents) , print dialog popup , should have contents have set content there's no content showing, there title of print dialog. if click again (second click) button has label of "print", contents of print dialog showing, ideas or clues what's going on? help, suggestions, recommendation make show?
here raw code
<button>print</button> <div id="print"> <table> <thead> <tr> <th>name</th> <th>gender</th> <th>age</th> <th>address</th> </tr> </thead> <tbody> <tr> <td>jason guatamala</td> <td>male</td> <td>18</td> <td>somewhere</td> </tr> </tbody> </table> </div> the jquery
$(document).ready(function(){ $("button").click(function(){ $("#print").print(); }); }); (function ( $ ) { $.fn.print = function(){ var content = $(this).html(); var style = '<style media="print" type="text/css">body{font-family: roboto, sans-serif;font-weight:500;font-size:13px;-webkit-print-color-adjust: exact;}table{width:100%;font-size:12px!important;}table tr td{border:1px solid rgba(0,0,0,.05);padding:3px;}table tr:nth-of-type(4n+1),table tr:nth-of-type(4n+2),table tr:nth-of-type(4n+3),table tr:nth-of-type(4n+4){background:#eee}table tr:nth-of-type(8n),table tr:nth-of-type(8n-1),table tr:nth-of-type(8n-2),table tr:nth-of-type(8n-3){background:#ddd}</style>'; var w = window.open('tt collection','', ''); w.document.write('<html><head><title>tt collection</title><link href="https://fonts.googleapis.com/css?family=roboto" rel="stylesheet" type="text/css">' + style + '</head><body><div style="font-size: 13px !important;" id="lf_print_main_wrapper">' + content + '</div></body></html>'); w.print(); w.close(); }; }( jquery ));
the problem dom of new window has not finished rendering before w.print() function called. 1 approach add print function script tag @ bottom of new window's html, executed after dom has finished rendering...
/* ... other code ... */ content + '</div><scr'+'ipt>window.print();</scr'+'ipt></body></html>'); // don't need w.print here anymore w.close(); fiddle: https://jsfiddle.net/b0qfsyxb/6/
Comments
Post a Comment