Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

สร้างปุ่ม Print หรือ Save Page ด้วย JavaScript

เรียนรู้สร้างปุ่มที่เปิด print หรือ save file window prompt ของ browser เมื่อคลิก

ปกติ print/save: Browser menu File → Print → Save as PDF หรือ Print

Shortcut: Cmd+P (Mac) / Ctrl+P (Windows)

แต่ถ้าอยากให้ง่ายกว่านั้น ให้ปุ่มที่เปิด print prompt ทันที:

สร้างปุ่ม

<button class="button-print-or-save-document">Print or Save Document</button>

ตั้งชื่อให้อ่านง่าย

Classes, variables, functions ควรใช้ชื่อ explicit (ยาว ชัดเจน) ไม่ใช่ abbreviated (สั้น เกลี้ยง) เช่น btn-pos-d — ไครอ่านไหว

ทำให้ปุ่ม Interactive ด้วย JS

const buttonPrintOrSaveDocument = document.querySelector(".button-print-or-save-document");
function printOrSave() {
  window.print();
}
buttonPrintOrSaveDocument.addEventListener("click", printOrSave);

reuse ปุ่มนี้ได้ทุกหน้าที่ต้องการ quick print/save option

โค้ดทำงานอย่างไร

  • Select ปุ่มด้วย class button-print-or-save-document เก็บใน const buttonPrintOrSaveDocument
  • สร้าง named function printOrSave() เรียก window.print
  • เพิ่ม event listener: listen click บนปุ่ม → เรียก printOrSave