What is the way to not kill the event handler in javascript?

I have a print function that allows me to print HTML content. I can click on the print button ok, but after I click the cancel button on the print layout all my javascript was killed. I can no longer do anything on the other button.

HTML:

<div id="printArea">
<p>Hello World</p>
</div>
<button type="button" id="printer">Print</button>

      

Javascript

$(document).on('click', '#printer',function(event){
        event.preventDefault();
        var printContents = document.getElementById("printArea").innerHTML;
        var originalContents = document.body.innerHTML;
        document.body.innerHTML = printContents;
        window.print();
        document.body.innerHTML = originalContents;
    });

      

I want to click the Print button and then return by clicking the Cancel button and also another button that can act as usual.

Any help would be much appreciated.

+3


source to share


2 answers


The best solution is to use css to hide / show the element, but for some reason, if this is not possible, in the script, do not replace the elements, but show / hide them

$(document).on('click', '#printer', function (event) {
    event.preventDefault();
    var $print = $("#printArea");
    //hide teh contents of the page
    $(document.body).wrapInner('<div style="display: none"></div>');
    //move a copy of the print area to the body and show it
    var $div = $('<div />').append($print.clone().contents()).appendTo(document.body);
    window.print();
    //remove the temporary print display
    $div.remove();
    //show back the original content
    $(document.body).children().contents().unwrap();
});

      



Demo: Fiddle

+3


source


When you use it document.body.innerHTML = originalContents;

, it creates new items that don't have any event functions associated with them.

It's better to use CSS to hide the elements you don't want to print, rather than change any HTML elements. CSS provides rules that only take effect after the page is printed.

Something like this should do the trick (you may need to tweek this depending on the structure of your HTML)



@media print {
  body * { display:none; }
  #printArea { display:block; }
}

      

Read this or this .

+2


source







All Articles