https://github.com/nonsalant/print-button
Web Component to print only a specific element (instead of the whole page)
https://github.com/nonsalant/print-button
button css light-dom print utility vanilla-javascript web-components
Last synced: about 1 year ago
JSON representation
Web Component to print only a specific element (instead of the whole page)
- Host: GitHub
- URL: https://github.com/nonsalant/print-button
- Owner: nonsalant
- License: mit
- Created: 2025-02-07T13:30:01.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2025-04-28T02:43:36.000Z (about 1 year ago)
- Last Synced: 2025-04-28T03:29:40.556Z (about 1 year ago)
- Topics: button, css, light-dom, print, utility, vanilla-javascript, web-components
- Language: JavaScript
- Homepage: https://codepen.io/nonsalant/pen/yyBmeBp
- Size: 2.93 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# print-button
Web Component to print only a specific element instead of the whole page (which is what `window.print()` does by default).
**[CodePen Demo](https://codepen.io/nonsalant/pen/yyBmeBp)**
## Examples
Print a specific element on the page:
```html
Print
```
Print the whole page:
```html
Print
```
Multiple print buttons on the same page:
```html
Print the 1st table
...
Print the 2nd table
...
```
Just the icon:
```html
```
## Attributes and Content
- `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.
- 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).
## Including the script
The script can be included anywhere on the page...
- as a module:
```html
```
- or as a non-module script tag:
```html
```
## How it works
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.
## Other notes
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:
```javascript
connectedCallback() {
setTimeout(() => {
//...
}, 150);
}
```
## Credits
- Print icon from [Ionicons 5: print-sharp](https://github.com/ionic-team/ionicons/blob/main/src/svg/print-sharp.svg).