"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > ✨ Simple trick for printing a div

✨ Simple trick for printing a div

Published on 2024-08-19
Browse:996

✨ Simple trick for printing a div

Advantages

  • Your page retains interactivity after print
  • Plays nice with frameworks
  • Doesn't require duplicating your UI for print

Steps

  1. Hide every content of the page when in print mode
  2. Make your target element visible in print mode

Step 1

@media print {
  body {
    visibility: hidden;
  }
}

Step 2

@media print {
  #section-to-print {
    top: 0;
    left: 0;
    position: absolute;
    visibility: visible;
  }
}

Then print

const button = document.querySelector('print-page');

button.addEventListener('click', () => window.print());

This method avoids the pitfall of loosing interactivity, other methods replace the entire page content with the static HTML thereby loosing interactivity.

const printContents = document.getElementById(divId).innerHTML;
const originalContents = document.body.innerHTML;

document.body.innerHTML = printContents;

window.print();

document.body.innerHTML = originalContents;
Release Statement This article is reproduced at: https://dev.to/joshuaamaju/simple-trick-for-printing-a-div-1kb5?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3