Ways to copy text to the clipboard in JavaScript
- Using the
navigator.clipboard
API: This is the recommended method. You can use thenavigator.clipboard.writeText()
method to write the text to the clipboard.
navigator.clipboard.writeText('Hello, World!').then(() => {
console.log('Text written to clipboard');
});
- Using the
copy()
method: This method is supported in most browsers. However, it may not work in older browsers.
const textToCopy = 'Hello, World!';
document.getElementById('copy-btn').addEventListener('click', function() {
document.execCommand('copy', false, textToCopy);
});
- Using the
setClipboardData()
method: This method is supported in Internet Explorer.
const textToCopy = 'Hello, World!';
const textarea = document.getElementById('textarea');
textarea.value = textToCopy;
const textAreaData = textarea.getData('Text');
navigator.clipboard.setClipboardData(new ClipboardItem({ 'text/plain': textAreaData })).then(() => {
console.log('Text written to clipboard');
});
- Using a library like
clipboard
: This library provides a simple way to copy text to the clipboard.
const clipboard = new ClipboardJS('copy-btn');
clipboard.on('success', function(e) {
console.log('Text written to clipboard');
});
Latest blog posts
Explore the world of programming and cybersecurity through our curated collection of blog posts. From cutting-edge coding trends to the latest cyber threats and defense strategies, we've got you covered.