Web Component to print only a specific element instead of the whole page (which is what window.print()
does by default).
Print a specific element on the page:
<print-button print-target=".element-to-print">
Print
</print-button>
Print the whole page:
<print-button>Print</print-button>
Multiple print buttons on the same page:
<print-button print-target="#table-1">
Print the 1st table
</print-button>
<table id="table-1">...</table>
<print-button print-target="#table-2">
Print the 2nd table
</print-button>
<table id="table-2">...</table>
Just the icon:
<print-button print-target=".element-to-print"></print-button>
print-target
attribute: CSS selector of the element to print. By default (if not provided), it prints the whole page except for the button itself.disabled
attribute: setting it on the custom element will disable the button inside.- Content: The text content of the button. If left empty,
aria-label="Print"
is added to the button (which will be a simple icon button).
Download the print-button.js
file and include it in your project.
As a module:
<script type="module" src="print-button.js"></script>
Or as a non-module script tag:
<script defer src="print-button.js"></script>
You can also include the script from a CDN:
<script type="module" src="https://unpkg.com/print-button/print-button.js"></script>
Or, for non-module usage:
<script defer src="https://unpkg.com/print-button/print-button.js"></script>
The printOnly()
method:
- starts at the target,
- adds a
.dont-print
class to its siblings, - moves to the parent and adds the class to its siblings,
- and continues up the DOM recursively adding the
.dont-print
class to all of the "uncles" (non-ancestors) of the target element.
The setTimeout(()=>{...})
wrapping the insides of the connectedCallback()
lifecycle method allows the script to be used as a non-module script tag (in addition to the module option) from anywhere on the page, including the header, by adding a ~4ms delay which should be enough for the DOM to be ready.
Increase the delay if needed (if your print-target
takes longer to load), e.g:
connectedCallback() {
setTimeout(() => {
//...
}, 150);
}
- Print icon from Ionicons 5: print-sharp.