How to print HTML content on click of a button, but not the page?
Quickly print a specific section of a webpage by wrapping the content in a div
with a unique id
, such as id="printableArea"
. Use a succinct JavaScript function to pop up the print dialog box for that section alone:
Pro Tip: Implementing Print-Specific Controls
Unfortunately, hitting the Ctrl+P
combo doesn't always give us exactly what we want. Sometimes, we're only interested in a specific part of the webpage. Here's how you'll handle this:
Content visibility using CSS media queries
When managing what gets printed, CSS media queries will be your best friend. This way, we'll only be shining light on the content we're actually interested in:
Printing dynamic content
Maybe your div
of interest isn't static. Worry not, JavaScript is just as dynamic! Let's modify the printContent
function to accept multiple content areas.
Now you can call printContent('id1', 'id2', 'id3')
to print multiple sections.
Printing Like A Pro!
Making print-specific CSS stylesheets
One neat trick is to have a dedicated stylesheet for print styles. This increases maintainability and straightforwardness of your CSS code:
Dynamically altering visibility using JavaScript
You can leverage JavaScript's prowess to change content visibility on the fly:
Ensure that your .print-mode
CSS class has appropriate visibility settings.
Polishing The User Experience
Minimize user interaction
Reduce the amount of clicks needed for one to print. Sounds obvious, but it's often overlooked.
Handle browser disparities gracefully
Each browser can treat print dialogues differently. Ensure you degrade gracefully when dealing with each.
Prevent page flickers and layout shifts
Karma points for preventing layout shifts during the printing process. The user should feel as if the page state hasn't changed, except for the printing that occurred.
Leave no side-effects
Once printing is done, the webpage should return to its original state without any loss of user inputs or state.
Was this article helpful?