DEV Community

Joshua Amaju
Joshua Amaju

Posted on

✨ 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;
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 2

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

Then print

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

button.addEventListener('click', () => window.print());
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)