Clipboard JS Tutorial | Copy Text to Clipboard in Javascript

Clipboard JS is library which will help you in copying text to clipboard in javascript. I hope you will like this quick overview.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">    
    <title>Document</title>
</head>
<body>
    
    <div>
        <input type="text" id="input1">
        <button data-clipboard-target="#input1">COPY</button>        
    </div>

    <div>
        <input type="text" id="input2">
        <button data-clipboard-target="#input2">COPY</button>        
    </div>

    <div>        
        <button data-clipboard-text="Hello World">COPY</button>        
    </div>

    <div>
        <textarea name="" id="" cols="30" rows="10"></textarea>
    </div>

    <script src="https://unpkg.com/clipboard@2/dist/clipboard.min.js"></script>
    <script src="script.js"></script>
</body>
</html>
let buttons = document.querySelectorAll('button');

let clipboard = new ClipboardJS(buttons);


clipboard.on('success', function(e) {
    console.info('Action:', e.action);
    console.info('Text:', e.text);
    console.info('Trigger:', e.trigger);

    e.clearSelection();
});

clipboard.on('error', function(e) {
    console.error('Action:', e.action);
    console.error('Trigger:', e.trigger);
});


console.log(ClipboardJS.isSupported());
body {
    background: #2c3e50;
}

div {
    margin-bottom: 10px;
}
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •