How to Copy Text to Clipboard using JavaScript or jQuery

In this tutorial, we will see multiple examples of copying text in the clipboard, including execCommand and via clipboard API and we will also see how we can use execcommand with jQuery.

However, this tutorial contains below example: 

  1. Using navigator.clipboard.writeText (modern browsers)
  2. Using execCommand (deprecated, but widely supported)
  3. Copy Text to Clipboard using jQuery
How to Copy Text to Clipboard using JavaScript or jQuery

First, we have to create an HTML structure so we can run our javascript function on button click.

        
        <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>How to Copy Text to Clipboard using JavaScript or jQuery
    </title>

    <style>
        * {
            font-family: Arial, Helvetica, sans-serif;
            margin: 0px;
            padding: 0;
            box-sizing: border-box;
        }

        .abh_container {
            width: 100%;
            max-width: 1024px;
            margin: auto;
            padding: 15px;
        }

        textarea.message_to_coppied {
            width: 50%;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin: 10px 0;
            padding: 5px;
        }

        label {
            display: block;
            margin-top: 15px;
        }

        .abh_btn {
            padding: 10px;
            background: #6213d3;
            border: 0px;
            border-radius: 4px;
            color: #fff;
            outline: 0px;
            cursor: pointer;
        }

        .abh_btn:hover {
            background: #df1c7f;
        }
    </style>
</head>

<body>
    <div class="abh_container">
        <h1> Copy Text to Clipboard using JavaScript</h1>
        <div class="row">
            <div class="message-input">
                <label for="message_to_coppied">Message: </label>
                <textarea id="message_to_coppied" rows="5" class="message_to_coppied">This is text that has to be copied when clicking on copy text button...
                </textarea>
            </div>
        </div>
        <div class="row">
            <button onclick="copyToClipboard('message_to_coppied', 'copy_btn')" type="button" id="copy_btn"
                class="abh_btn">Copy to clipboard</button>
        </div>
        <div class="row">
            <div class="message-input">
                <label for="">Test Copied text here: </label>
                <textarea rows="5" class="message_to_coppied"></textarea>
            </div>
        </div>
    </div>

</body>

</html>
        
    

Using execCommand (deprecated, but widely supported):

The execCommand method is deprecated in javascript but widely supported including all browsers.

Try It
        
        function copyToClipboard(textareaId, btn_id) {
            var textarea = document.getElementById(textareaId);
            var btn = document.getElementById(btn_id);

            if (textarea) {
                // Create a temporary textarea element
                var tempTextarea = document.createElement('textarea');
                tempTextarea.value = textarea.value;

                // Set it to be invisible
                tempTextarea.style.position = 'fixed';
                tempTextarea.style.opacity = 0;

                // Append it to the document
                document.body.appendChild(tempTextarea);

                // Select and copy the text
                tempTextarea.select();
                document.execCommand('copy');

                // Remove the temporary textarea
                document.body.removeChild(tempTextarea);

                btn.innerHTML = "Copied";
                // Change the button text after 2 seconds to normal
                setTimeout(function () {
                    btn.innerHTML = "Copy text to clipboard";
                }, 2000);
            } else {
                console.error('Textarea element not found');
            }
        }
        
    

Related Post

Copy Text to Clipboard using jQuery

Try It
        
        $(document).ready(function () {
            $('body').on('click', '#copy_btn', function () {
                // Get the text from the textarea
                var textToCopy = $("#message_to_copied").val();

                // Create a temporary textarea element
                var tempTextarea = $("<textarea>");

                // Set its value to the text to be copied
                tempTextarea.val(textToCopy);

                // Append it to the body
                $("body").append(tempTextarea);

                // Select and copy the text
                tempTextarea.select();
                document.execCommand("copy");

                // Remove the temporary textarea
                tempTextarea.remove();

                // Change the button text after 2 seconds
                $(this).html("Copied");
                setTimeout(function () {
                    $("#copy_btn").html("Copy text to clipboard");
                }, 2000);
            });
        });
        
    

Using navigator.clipboard.writeText (clipboard API)

This will select the text in the textarea and copy it to the clipboard when the button is clicked.  this method is widely supported including all modern browsers.

Try It
        
        function copyToClipboard(elementId, btn_id) {
            var textarea = document.getElementById(elementId);
            var btn = document.getElementById(btn_id);

            if (navigator.clipboard) {
                navigator.clipboard.writeText(textarea.value)
                    .then(() => {
                        btn.innerHTML = "Copied";
                        console.log('Text successfully copied to clipboard');

                        // Change button text back to original after 2 seconds
                        setTimeout(function () {
                            btn.innerHTML = 'Copy to Clipboard';
                        }, 2000);
                    })
                    .catch(err => {
                        console.error('Unable to copy text to clipboard', err);
                    });
            } else {
                console.error('Clipboard API not supported');
            }
        }
        
    

Leave a comment