I have a page that has some content to be printed. At the moment of the printing, some divs must be hidden and just one must appear. The code works fine on Chrome, Firefox and IE, but not on Safari.
Here is my JS:
$(".printButton").on("click", function (event) {
event.preventDefault();
$("form").attr("style", "display: none !important");
$("body").append("<div class='divToBePrinted' style='display: block !important;'></div>");
$(".content").clone().appendTo('.divToBePrinted');
window.print();
$("form").removeAttr("style");
$(".divToBePrinted").remove();
});
Here is my simplified HTML:
<html>
<body>
<form>
<!-- Other content -->
<div class="content">
Content to be printed.
</div>
<button class="printButton"></button>
<!-- Other content -->
</form>
</body>
</html>
On Safari, the window.print() seems to execute before the event.preventDefault(), catching the entire page to print.
EDIT: I tried to use setTimeout like below, but it didn't work. There is a CSS specific for printing, but the file is very large. I tried to remove it, but I've got the same result: works fine in all browser but not on Safari.
JS with setTimeout:
$(".printButton").on("click", function (event) {
event.preventDefault();
$("form").attr("style", "display: none !important");
$("body").append("<div class='divToBePrinted' style='display: block !important;'></div>");
$(".content").clone().appendTo('.divToBePrinted');
//setTimeout(window.print, 1000); -- I tried this way
// And this way
setTimeout(function () {
window.print();
$("form").removeAttr("style");
$(".divToBePrinted").remove();
}, 0);
});
EDIT 2: I tried to put 1000 milliseconds to setTimeout and it worked the most of times, but its not the final solution and I'll do a new research to find the better way.
setTimeout(function () {
window.print();
$("form").removeAttr("style");
$(".divToBePrinted").remove();
}, 1000);
It would appear that the onafterprint event fires almost immediately after window.print.
On most browsers this event is not called until the user clicks print on the Print Dialog but on Safari it seems to fire as the Print Dialog shows up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With