I have a page on which there is text to print. At the time of printing, some divs should be hidden, and only one should 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>
<div class="content">
Content to be printed.
</div>
<button class="printButton"></button>
</form>
</body>
</html>
In Safari, window.print () seems to be executed before event.preventDefault (), capturing the entire page for printing. A.
EDIT: I tried using setTimeout as shown below, but that did not work. There is CSS for printing, but the file is very large. I tried to remove it, but I have the same result: it works fine in all browsers, but not in 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(function () {
window.print();
$("form").removeAttr("style");
$(".divToBePrinted").remove();
}, 0);
});
EDIT 2: I tried setting 1000 milliseconds to setTimeout, and it worked many times, but this is not the final solution, and I will do a new study to find the best way.
setTimeout(function () {
window.print();
$("form").removeAttr("style");
$(".divToBePrinted").remove();
}, 1000);