Hi I'm using svelte for a side project i am doing and i want to print a receipt and not the entire page. is there a way to do it? i saw some other posts talking about how to print a div element using plain JavaScript but this doesn't work in svelte.
example code i want to print only the element with the class printable
<div class="printable">
<h1>hello world</h1>
</div>
<div class="navbar">
<a href="/">home</a>
<a href="/next">next</a>
<a href="/profile">profile</a>
</div>
You can use a @media query or use events (beforeprint/afterprint) and local state to show/hide things.
In terms of targeting elements, it is easier if you invert the logic and mark elements to remove when printing. It is easy to hide all elements that do not have the class, but that would by default include the h1 inside the printable element.
For example:
<div>
<h1>hello world</h1>
</div>
<div class="navbar not-printable">
<a href="/">home</a>
<a href="/next">next</a>
<a href="/profile">profile</a>
</div>
<style>
@media print {
.not-printable { display: none; }
}
</style>
(If elements are spread over multiple files, you might want to move this to a global style sheet because of the component style scoping.)