Alex
Alex

Reputation: 1469

How to copy text from a div to clipboard

Here is my code for when the user clicks on this button:

<button id="button1">Click to copy</button>

How do I copy the text inside this div?

<div id="div1">Text To Copy</div>

Upvotes: 105

Views: 196305

Answers (13)

user3783700
user3783700

Reputation: 11

<!--My final edit source-->

<style type="text/css">
  div,
  a {
    font-size: 22px;
    font-family: tahoma;
  }
</style>
<html>
<body>
  <div id="a">My name is Mousa Khaaaa</div>
  <br>
  <a onclick="copyDivToClipboard()">Copy from here</a>
  <script>
    function copyDivToClipboard() {
      var range = document.createRange();
      range.selectNode(document.getElementById("a"));
      window.getSelection().removeAllRanges(); // clear current selection
      window.getSelection().addRange(range); // to select text
      document.execCommand("copy");
      window.getSelection().removeAllRanges(); // to deselect
      alert("Copied")
    }
  </script>
</body>
</html>

Upvotes: 1

Dan
Dan

Reputation: 1571

The up-to-date method to do this is to use the navigator.clipboard object like so:

const synopsis = document.getElementById('mydiv');
navigator.clipboard.writeText(synopsis.innerText);

Upvotes: 3

Andrii Radkevych
Andrii Radkevych

Reputation: 3442

Here you can see code which works on different browsers, including iOS.

const copyToClipboard = (id) => {
  var r = document.createRange();
  r.selectNode(document.getElementById(id));
  window.getSelection().removeAllRanges();
  window.getSelection().addRange(r);
  document.execCommand("copy");
  window.getSelection().removeAllRanges();
};

const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;

const copyIOS = (id) => {
  const text = document.getElementById(id).innerHTML;

  if (!navigator.clipboard) {
    const textarea = document.createElement("textarea");

    textarea.value = text;
    textarea.style.fontSize = "20px";
    document.body.appendChild(textarea);

    const range = document.createRange();
    range.selectNodeContents(textarea);

    const selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    textarea.setSelectionRange(0, 999999);

    document.execCommand("copy");

    document.body.removeChild(textarea);
  }

  navigator.clipboard.writeText(text);
};

const copyTextById = (id) => {
  if (isIOS) {
    return copyIOS(id);
  }
  copyToClipboard(id);
};

window.copyTextById = copyTextById
<div id="text">Text which you will copy</div>

<button onclick="copyTextById('text')">Click me</button>

Upvotes: 5

user4822420
user4822420

Reputation: 54

The solutions above do not work for the content editable div. A few more steps are needed to copy its content to the clipboard.

Here is how to copy div contenteditable to the clipboard. Selecting text on the iphone and Android is not always easy. With one Copy button you can copy all the content.

<div id="editor1" contenteditable="true"></div> 

<button id="button1" onclick="CopyToClipboard()">COPY</button>

<script>

function CopyToClipboard() {

    var copyBoxElement = document.getElementById('editor1');
    copyBoxElement.contenteditable = true;
    copyBoxElement.focus();
    document.execCommand('selectAll');
    document.execCommand("copy");
    copyBoxElement.contenteditable = false;
    alert("Text has been copied")
}

</script>

Upvotes: 2

OsowoIAM
OsowoIAM

Reputation: 81

<div id='myInputF2'> YES ITS DIV TEXT TO COPY  </div>

<script>

    function myFunctionF2()  {
        str = document.getElementById('myInputF2').innerHTML;
        const el = document.createElement('textarea');
        el.value = str;
        document.body.appendChild(el);
        el.select();
        document.execCommand('copy');
        document.body.removeChild(el);
        alert('Copied the text:' + el.value);
    };
</script>

more info: https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f

Upvotes: 6

Eldho NewAge
Eldho NewAge

Reputation: 1333

Both examples work like a charm :)

  1. JAVASCRIPT:

    function CopyToClipboard(containerid) {
      if (document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(containerid));
        range.select().createTextRange();
        document.execCommand("copy");
      } else if (window.getSelection) {
        var range = document.createRange();
        range.selectNode(document.getElementById(containerid));
        window.getSelection().addRange(range);
        document.execCommand("copy");
        alert("Text has been copied, now paste in the text-area")
      }
    }
    <button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>
    <br /><br />
    <div id="div1">Text To Copy </div>
    <br />
    <textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>

  2. JQUERY (relies on Adobe Flash): https://paulund.co.uk/jquery-copy-to-clipboard

Upvotes: 104

AmaliaKalio
AmaliaKalio

Reputation: 66

Made a modification to the solutions, so it will work with multiple divs based on class instead of specific IDs. For example, if you have multiple blocks of code. This assumes that the div class is set to "code".

<script>
        $( document ).ready(function() {
            $(".code").click(function(event){
                var range = document.createRange();
                range.selectNode(this);
                window.getSelection().removeAllRanges(); // clear current selection
                window.getSelection().addRange(range); // to select text
                document.execCommand("copy");
                window.getSelection().removeAllRanges();// to deselect
            });
        });
    </script>

Upvotes: 2

iamafasha
iamafasha

Reputation: 794

Non of all these ones worked for me. But I found a duplicate of the question which the anaswer worked for me.

Here is the link

How do I copy to the clipboard in JavaScript?

Upvotes: 1

romin21
romin21

Reputation: 1651

The accepted answer does not work when you have multiple items to copy, and each with a separate "copy to clipboard" button. After clicking one button, the others will not work.

To make them work, I added some code to the accepted answer's function to clear text selections before doing a new one:

function CopyToClipboard(containerid) {
    if (window.getSelection) {
        if (window.getSelection().empty) { // Chrome
            window.getSelection().empty();
        } else if (window.getSelection().removeAllRanges) { // Firefox
            window.getSelection().removeAllRanges();
        }
    } else if (document.selection) { // IE?
        document.selection.empty();
    }

    if (document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(containerid));
        range.select().createTextRange();
        document.execCommand("copy");
    } else if (window.getSelection) {
        var range = document.createRange();
        range.selectNode(document.getElementById(containerid));
        window.getSelection().addRange(range);
        document.execCommand("copy");
    }
}

Upvotes: 25

Arun Tom
Arun Tom

Reputation: 889

I was getting selectNode() param 1 is not of type node error.

changed the code to this and its working. (for chrome)

function copy_data(containerid) {
  var range = document.createRange();
  range.selectNode(containerid); //changed here
  window.getSelection().removeAllRanges(); 
  window.getSelection().addRange(range); 
  document.execCommand("copy");
  window.getSelection().removeAllRanges();
  alert("data copied");
}
<div id="select_txt">This will be copied to clipboard!</div>
<button type="button" onclick="copy_data(select_txt)">copy</button>
<br>
<hr>
<p>Try paste it here after copying</p>
<textarea></textarea>

Upvotes: 10

J. Garc&#237;a
J. Garc&#237;a

Reputation: 1919

I tried the solution proposed above. But it was not cross-browser enough. I really needed ie11 to work. After trying I got to:

    <html>
        <body>
            <div id="a" onclick="copyDivToClipboard()"> Click to copy </div>
            <script>
                function copyDivToClipboard() {
                    var range = document.createRange();
                    range.selectNode(document.getElementById("a"));
                    window.getSelection().removeAllRanges(); // clear current selection
                    window.getSelection().addRange(range); // to select text
                    document.execCommand("copy");
                    window.getSelection().removeAllRanges();// to deselect
                }
            </script>
        </body>
    </html>

Tested with firefox 64, Chrome 71, Opera 57, ie11(11.472.17134.0), edge( EdgeHTML 17.17134)

Update March 27th, 2019.

For some reason document.createRange() didn't work before with ie11. But now properly returns a Range object. So is better to use that, rather than document.getSelection().getRangeAt(0).

Upvotes: 146

loretoparisi
loretoparisi

Reputation: 16311

This solution add the deselection of the text after the copy to the clipboard:

function copyDivToClipboard(elem) {
    var range = document.createRange();
    range.selectNode(document.getElementById(elem));
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);
    document.execCommand("copy");
    window.getSelection().removeAllRanges();
}

Upvotes: 6

Aparna
Aparna

Reputation: 783

Adding the link as an Answer to draw more attention to Aaron Lavers' comment below the first answer.

This works like a charm - http://clipboardjs.com. Just add the clipboard.js or min file. While initiating, use the class which has the html component to be clicked and just pass the id of the component with the content to be copied, to the click element.

Upvotes: 3

Related Questions