Learn how to make a button that opens your browser’s print or save file window prompt when you click on it.
If you want to print or save a page on any given website, you can go to your browser (usually the top left corner):
- Click on File → Print → and either click the Save button to save the file as a PDF document, or print it with your printer.
- Print/Save shortcut: cmd + p (Mac) / ctrl + p (Windows).
But what if you want to make it even easier for your user to print or save a page, by providing them with a print or save file button that instantly opens up the browsers Print prompt window on click?
No problem, first let’s create a button with a fitting class name:
<button class="button-print-or-save-document">Print or Save Document</button>
Make your code easy to read for everyone!
For things like classes, variables, and functions it’s generally better to use longer, explicit names as we do on the button above. As opposed to short, abbreviated (implicit) names, like btn-pos-d
. Nobody likes reading that.
Now let’s make the button interactive with JavaScript:
const buttonPrintOrSaveDocument = document.querySelector(
".button-print-or-save-document"
)
function printOrSave() {
window.print()
}
buttonPrintOrSaveDocument.addEventListener("click", printOrSave)
Now you can reuse this button element on any web page where you want to provide a quick print or save document option to your users.
How the code works
- First, we select the button with the
button-print-or-save-document
class and store a reference to it in aconst
variable (buttonPrintOrSaveDocument
). - Then we make a named function declaration
printOrSave()
that executes thewindow.print
method when it’s called. - Finally, we set up an event listener with two arguments: one that listens for a
click
event on the button element, and another to call theprintOrSave
function.