Di bawah ini kita akan mempelajari cara menyalin teks ke clipboard dengan CSS dan JavaScript.
Klik pada button di samping field text untuk menyalin teks dari field teks.
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .tooltip { position: relative; display: inline-block; } .tooltip .tooltiptext { visibility: hidden; width: 140px; background-color: #555; color: #fff; text-align: center; border-radius: 6px; padding: 5px; position: absolute; z-index: 1; bottom: 150%; left: 50%; margin-left: -75px; opacity: 0; transition: opacity 0.3s; } .tooltip .tooltiptext::after { content: ""; position: absolute; top: 100%; left: 50%; margin-left: -5px; border-width: 5px; border-style: solid; border-color: #555 transparent transparent transparent; } .tooltip:hover .tooltiptext { visibility: visible; opacity: 1; } </style> </head> <body> <p>Klik pada button di sebelah field text untuk menyalin teks dari bidang teks. Coba tempel teks (mis. Ctrl + v) setelah itu di jendela lain, untuk melihat efeknya.</p> <input type="text" value="Avengers" id="myInput"> <div class="tooltip"> <button onclick="myFunction()" onmouseout="outFunc()"> <span class="tooltiptext" id="myTooltip">Copy to clipboard</span> Copy text </button> </div> <script> function myFunction() { var copyText = document.getElementById("myInput"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); var tooltip = document.getElementById("myTooltip"); tooltip.innerHTML = "Copied: " + copyText.value; } function outFunc() { var tooltip = document.getElementById("myTooltip"); tooltip.innerHTML = "Copy to clipboard"; } </script> </body> </html>
Cara Menyalin Text Ke Clipboard
Langkah 1) Tambahkan HTML:
Contoh
<!-- field teks --> <input type="text" value="Avengers" id="myInput"> <!-- Button yang digunakan untuk menyalin teks --> <button onclick="myFunction()">Copy text</button>
Langkah 2) Tambahkan JavaScript:
Contoh
function myFunction() {
/* dapatkan field teks */
var copyText = document.getElementById("myInput");
/* Select field text */
copyText.select();
copyText.setSelectionRange(0, 99999); /* untuk perangkat mobile */
/* Salin teks di dalam field teks */
document.execCommand("copy");
/* Peringatkan teks yang disalin */
alert("Copied the text: " + copyText.value);
}Tampilkan Teks yang Disalin di Tooltip
Tambahkan CSS:
Contoh
.tooltip {
position: relative;
display: inline-block;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 140px;
background-color: #555;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px;
position: absolute;
z-index: 1;
bottom: 150%;
left: 50%;
margin-left: -75px;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip .tooltiptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}