Introduction
Copying text programmatically in JavaScript can be a handy skill, especially when working on web applications that require efficient user interactions. Whether you want to enhance the user experience by simplifying the copy-paste process or creating a custom feature, JavaScript provides a straightforward way to achieve this. This article will explore how to copy text programmatically using JavaScript.
How to copy Text Programmatically in JavaScript
Clipboard API
The Clipboard API is a powerful tool that allows developers to interact with the clipboard programmatically. To copy text, we can use the writeText
method, which is part of the Clipboard API.
JavaScript code
function copyFunction(){
var data = document.getElementById("textData");
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(data);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand("Copy");
alert("Copy ho gaya");
}
HTML code
<center>
<h1>Click To Copy to clipbord</h1>
<hr>
<fieldset id="textData" style="width:80%; height: 400px;" contenteditable="true">
</fieldset>
<button onclick="copyFunction()">copy</button>
</center>