How can I prevent my JavaScript event handlers from stopping after closing the print dialog?

I developed a printing feature that allows me to display the HTML content for printing. When I press the print button, it works correctly, but if I hit the cancel button on the print dialog, it causes all my JavaScript functions to fail. After that, I can’t interact with any other buttons anymore.

HTML:

<div id="printContainer">
<p>Hello World</p>
</div>
<button type="button" id="printBtn">Print</button>

JavaScript:

$(document).on('click', '#printBtn', function(event){
    event.preventDefault();
    var contentToPrint = document.getElementById("printContainer").innerHTML;
    var previousContent = document.body.innerHTML;
    document.body.innerHTML = contentToPrint;
    window.print();
    document.body.innerHTML = previousContent;
});

I need to ensure that after printing or canceling, I can still use other buttons as normal. Any assistance would be greatly appreciated.

Try preserving the original document structure with a print-only window. Here's an updated approach:

$(document).on('click', '#printBtn', function(event){
    event.preventDefault();
    var contentToPrint = document.getElementById("printContainer").innerHTML;
    var newWindow = window.open('', '_blank');
    newWindow.document.write(contentToPrint);
    newWindow.document.close();
    newWindow.focus();
    newWindow.print();
    newWindow.close();
});

This way, you isolate the printing process, avoiding interference with your main page.