Copy Paste with Java Script

Copy Paste with Java Script

Oktober 16, 2022
copy paste

Hari ini kita akan belajar mengenai cara copy paste tulisan menggunakan Java Script. Sebelum memulai tutorialnya, saya akan coba menjelaskan apa itu copy dan paste.

Apa itu Copy?

Secara umum copy memiliki definisi salin (menyalin), meniru, mencontoh, dan yang lainnya. Dalam definisi lain kata copy itu adalah sebuah system atau bisa juga perintah ntuk menggandakan sebuah kata, paragraf, tabel, gambar, dan object apa pun.

Apa itu Paste?

Sedangkan untuk Paste sendiri adalah perintah lanjutan dari proses copy, yaitu meletakan sesuatu yang sudah diberikan perintah copy.

Berikut adalah beberapa cara untuk melakukan perintah Copy dengan Java Script :

COPY

1. Dengan Navigator Clipboard
function copyAtuh() {
    // Get the text field
    var copyText = document.getElementById("test");
  
    // Select the text field
    copyText.select();
    copyText.setSelectionRange(0, 99999); // For mobile devices
  
     // Copy the text inside the text field
    navigator.clipboard.writeText(copyText.value);
  
   // Log the copied text
   console.log("Copied the text: " + copyText.value);
  }
2. Dengan ExecCommand
function copyAtuh(){
   var copyText = document.getElementById("test");
   // Select the text field
   copyText.select();
   
   // Copy the text inside the text field
   document.execCommand("copy");
   
   // Log the copied text
   console.log("Copied the text: " + copyText.value);
}

PASTE

1. Dengan Navigator Clipboard
async function pasteAtuh() {
  // paste data from clipboard
  const pastetext = await navigator.clipboard.readText();
  var ta =  document.getElementById("pastetext");
  ta.innerHTML = pastetext;
}  
2. Dengan ExecCommand
// paste data from clipboard
document.execCommand("paste")

CUT

Apa itu Cut?

Tambahan informasi mengenai CUT, berbeda dengan copy yang memiliki arti menggandakan, untuk Cut sendiri memiliki arti memotong ataupun memindahkan seuatu objek baik itu kata, paragraf, tabel, gambar, dan object apa pun.

Dengan ExecCommand
// Cut data
document.execCommand("cut")
Referensi

https://www.w3schools.com/howto/howto_js_copy_clipboard.asp


Join our subscriber list to get the latest news, updates and special offers sent straight to your mailbox.