Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Window.print Issues

here is my problem I have a code that implement the window.print but the problem is when I close the window print and go back to my page my print button is not working anymore.

$(function(){
    $('#button1').click(function()
        {
          $('head').append('<link rel="stylesheet" href="<?php echo base_url() ?>assets/weekly/style/weekly.css" type="text/css"/>');
           var printContents = document.getElementById('data').innerHTML;
           var originalContents = document.body.innerHTML;
           document.body.innerHTML = printContents;
           window.print();
           document.body.innerHTML = originalContents;
           //window.location = document.body.innerHTML;       
           //location.reload(); 
        });
     }); 

But when I add the location.reload() (see I comment it) the print button is working again but it loads the previous data not the current data that is why I don't want to use the location.reload(). Is there other solution or approach to my problem?

like image 498
user2046410 Avatar asked Jun 26 '13 09:06

user2046410


2 Answers

You should really be using a print-specific CSS stylesheet for this, but if you want to accomplish your goal in that way, maybe this would work better:

$(function(){
    $('#button1').click(function(){
        $('head').append('<link rel="stylesheet" href="<?php echo base_url() ?>assets/weekly/style/weekly.css" type="text/css"/>');
         var printContents = $( $('#data').html() );
         var originalContents = $('body > *').hide();
         $('body').append( printContents );
         window.print();
         printContents.remove();
         originalContents.show();
      });
 }); 

Make a new element using the innerHTML of the 'data' element. Hide all the children of the body tag. Append the new element to the body tag. Print. Remove the new element. Show the original contents again.

This is still kind of messy, but you shouldn't lose your events.

like image 93
nderscore Avatar answered Sep 27 '22 22:09

nderscore


I fixed a similar problem by just opening a new window with only the content I wanted to print like this:

function printPage(htmlstring){

    var boiler  = "put any styling or js scripts here to make it look right";
        boiler += "<div id='print-page-content'>\n</div>\n";

    var PrintWindow = window.open("","newwin", height=600, width=800, toolbar=no, menubar=no");
    PrintWindow.document.write(boiler);
    $(PrintWindow.document).find("#print-page-content").append(htmlstring);
    $(PrintWindow).ready(function(){
        PrintWindow.print();
    });
}

Then just call it by:

printPage(document.body.innerHTML);
like image 34
QuantumDebris Avatar answered Sep 27 '22 22:09

QuantumDebris