0

I have this javascript code attached that puts some content into a popup window and then tries to print it:

$(".print_friendly_popup").click(function() {
    var target = $(this).data('print-target');
    var left = (screen.width/2)-(500/2);
    var top = (screen.height/2)-(500/2);
    var win = window.open("", "test", "width=500,height=500 top=" + top + ", left=" + left);

    if(target == 'review') {
        win.document.write($('#print_friendly_review').html());
    } else if(target == 'essay') {
        win.document.write($('#print_friendly_essay').html());
    }
    win.print();
    win.close();
});

The problem is sometimes the call to win.document.write takes too long and the window tries to print a blank screen. How do I wait for window.document to be written to before firing print?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
snowflakekiller
  • 3,428
  • 6
  • 27
  • 45
  • Tried a `setTimeout()`? – Rory McCrossan Oct 06 '16 at 07:09
  • 1. "document.write" isn't very "best-practice", I think I would change to a simple HTML append (or assign the HTML as a string to the proper element - faster) - than you can use "onLoad" event to see that all content have been loaded and do your "print" 2. I would go for a method that can set my "printed style" via CSS Media: "@media print" – Yonatan Ayalon Oct 06 '16 at 11:03
  • There's nothing wrong with using document.write for building popup window content. – JJJ Oct 06 '16 at 11:58

2 Answers2

2

So how about this: create some sort of "checker" to see if the window has the content in it, for example:

var checkForContent = function () {
  setTimeout(function () {
    var content = win.document.querySelector('body').innerHTML

    if (content.length) {
      win.print()
      win.close()
    } else {
      checkForContent()
    }
  }, 200)
}

This way you're politely waiting for the content to render before printing.

Ahmed Nuaman
  • 12,662
  • 15
  • 55
  • 87
1

Try

win.onload = function(e){ 
    //..... your codes 
}
T.Todua
  • 53,146
  • 19
  • 236
  • 237