How To Copy Text To Clipboard On Button Click Using jQuery

In this article, I’m going to show you that how can we copy text to a clipboard with a button click using jQuery.

Below Is The Html Code

<p style="font-size:35px;text-align:center;margin-top:15px;">Copy a TEXT to Clipboard on a Button-Click</p>

<div style="text-align:center;">
    <br />
    <br />
    <label>Text 1: </label> <span id="p1">Hello, I'm Chand Dakhara</span>
    <br />
    <label>Text 2: </label> <span id="p2">I'm a Web Developer</span><br />
    <br />
    <br />
    <button onclick="copy('#p1')" class="btn btn-primary">Copy TEXT 1</button>
    <button onclick="copy('#p2')" class="btn btn-primary">Copy TEXT 2</button>

    <br /><br /><input class="form-control" type="text" id="" placeholder="Paste Here" style="display: initial;" />
</div>

Here Is The jQuery Function

function copy(element) {
        var $temp = $("<input>");
        $("body").append($temp);
        $temp.val($(element).text()).select();
        document.execCommand("copy");
        $temp.remove();
    }

Explanation

The above function will be called when someone clicks on any button. In this function, I’m passing the id of the HTML control which we will use to copy a text. Next, I’m creating a temporary input control and append it to our HTML document, and set its value with the specific clicked text, and then select its value. After that fire, the copy command and then remove that temporary control.

Output

Copy Text

Submit a Comment

Your email address will not be published. Required fields are marked *

Footer Logo

Subscribe

Select Categories