1

Is there any way to print a div using knockout, durandal and html 5?

I am using knockoutjs and durandal to build my application in HTML 5. I am trying to print a div. I am using the following code

function printDiv(divID) {
    //Get the HTML of div
    var divElements = document.getElementById(divID).innerHTML;
    //Get the HTML of whole page
    var oldPage = document.body.innerHTML;

    /Reset the page's HTML with div's HTML only
    document.body.innerHTML = 
        "<html><head><title></title></head><body>" + 
        divElements + "</body>";

    //Print Page
    window.print();

    //Restore orignal HTML
    document.body.innerHTML = oldPage;
}

<input type="button" value="Print 1st Div" 
       data-bind="function(){printDiv('printablediv')}" />

The div is getting printed but after that I am kind of losing the context of my page. I am clicking on the page but nothing is happening.

GôTô
  • 7,974
  • 3
  • 32
  • 43
user3004443
  • 133
  • 1
  • 1
  • 16
  • I think you'd better not change your page and [print a popup](http://stackoverflow.com/questions/12997123/print-specific-part-of-webpage) – GôTô Jul 01 '14 at 08:25

1 Answers1

0
  var print = function () {
        window.print();
   }


  viewModel = {
        activate: activate,
        attached: attached,
        print: print
  }
  return viewModel;

HTML:

   <input type="button" value="Print 1st Div" data-bind="click: print" />

CSS:

@media print {
   body *:not(.printablediv){display:none!important};
}
Gildas.Tambo
  • 22,173
  • 7
  • 50
  • 78