Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fadi-george/6eb6bc122e0e1351459930b7e3e90170 to your computer and use it in GitHub Desktop.
Save fadi-george/6eb6bc122e0e1351459930b7e3e90170 to your computer and use it in GitHub Desktop.
// js
const modifyClassList = (
method: string,
ids: Array<string>,
classStyle: Array<string>,
) => {
let el: any;
ids.forEach((id: string) => {
el = document.querySelector(id);
if (el) {
classStyle.forEach((style: string) => {
el.classList[method](style);
});
}
});
};
export const printContent = (elemID: string) => {
// makes everything but the provided element visible (visible elements can still take up space)
modifyClassList('remove', ['body'], ['print-area']);
modifyClassList('add', [elemID], ['print-area']);
window.print();
// undo changes before the print
modifyClassList('add', ['body'], ['print-area']);
modifyClassList('remove', [elemID], ['print-area']);
};
// css
@media print {
body * {
visibility: hidden;
height: 0;
width: 0;
}
.print-area, .print-area * {
visibility: visible;
height: auto;
width: auto;
}
.print-area {
position: absolute;
left: 0;
top: 0;
width: 100vw;
max-width: 100vw;
overflow: unset;
}
}
// e.g.
printContent('#some-content');
<div>
<div>Won't be shown</div>
<div id="some-content">Should be shown</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment