Javascript - How to copy text to clipboard

Introduction

Clipboard.js is a Javascript library to copy text content to clipboard

Setup

Via CDN providers

Via npm package

npm install clipboard --save

##3 Usage
Using HTML5 data atrribute ‘‘data-clipboard-target’’ and ‘‘data-clipboard-action’’

‘‘Copy text’’ - The code below will copy text from textarea to clipboard when event click of button Copy to clipboard is trigger

<textarea id="bar">Text to be copied...</textarea>
<!-- Trigger -->
<button class="btn" data-clipboard-action="copy" data-clipboard-target="#bar">
    Copy to clipboard
</button>

‘‘Cut text’’ - The code below will cut text from textarea to clipboard when event click of button Copy to clipboard is trigger

<textarea id="bar">Text to be cut...</textarea>
<!-- Trigger -->
<button class="btn" data-clipboard-action="cut" data-clipboard-target="#bar">
    Cut to clipboard
</button>

Demo

https://quantmscubism.github.io/clipboard.html

Reference



:sunglasses::sunglasses::sunglasses::sunglasses::sunglasses:

Javascript có hỗ trợ phương thức execCommand(“copy”) Demo. Vậy tại sao phải sử dụng thư viện này?

2 Likes

Ngoài ra còn Clipboard API nữa.
Dùng clipboard.js cũng tốt, thư viện này dùng execCommand('copy') nhưng dễ sử dụng hơn, hỗ trợ data attributes.

3 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?