Appreciate your assistance! I'm currently working on a solution to print a specific div using CSS Media queries. When the user clicks on print, I want to hide all other elements except for the body div they chose. However, I'm facing an issue where the hidden elements still appear in their original positions during printing due to the 'hidden' property. Display:none isn't feasible as it disrupts dynamically generated elements. Any advice on how to ensure that the selected elements are printed front and center on the first page would be greatly appreciated! Below is my CSS code for printing:
<style>
/*HIDING ALL ELEMENTS EXCEPT THE PRINTED ONE*/
@media print {
/*Hide all HTML elements*/
body * {
visibility: hidden;
}
/*Make chosen elements and their children visible*/
.section-to-print-head, .section-to-print-body, .section-to-print-head *, .section-to-print-body * {
visibility: visible;
display: block;
}
/*POSITION OF HEAD*/
.section-to-print-head {
position: absolute;
left: 0;
top: 0;
width: 100%;
page-break-after: avoid;
display: block;
}
/*POSITION OF BODY*/
.section-to-print-body {
position: absolute;
left: 5;
top: 0;
width: 100%;
z-index: 100;
}
.section-to-print-body:last-child {
page-break-after: avoid;
}
}
</style>
Here's the HTML snippet with the button and onclick function:
<div class="row infoAreaToPrint">
<div class="col-lg-5">
<div class="card">
<div class="card-body">
<p class="h4 border-bottom mb-0">
Customer: <?php echo $custName ?></p>
<span>
<button
onclick="printThisTableDiv('.infoAreaToPrint')">Print Info</button>
</span>
This is the function I use to hide all elements except the one intended for printing:
function printThisTableDiv(tableID) {
let existingTags = document.querySelectorAll('.section-to-print-body');
let i;
for (i = 0; i < existingTags.length; i++) {
existingTags[i].classList.remove('section-to-print-body');
}
document.querySelector(tableID).classList.add("section-to-print-body");
window.print();
};