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();

        alert("Copy ho gaya");


HTML code

    <h1>Click To Copy to clipbord</h1>


        <fieldset id="textData" style="width:80%; height: 400px;" contenteditable="true">        
        <button onclick="copyFunction()">copy</button>


Download the example file 👇


Leave a Reply

Your email address will not be published.