-1

I have some divs in my HTML and I want to copy the contents of a div when I click on that div.

<div class="container">Hello</div>
<div class="container">World</div>
<div class="container">LearnJS</div>

So when I click on first div, it will copy the "Hello" on the clipboard.

I searched this site and found some zeroclipboard and clipboard.js, but I don't know how can I use it; I'm new to jQuery.

How would I write a function that copies the div's inner text onclick?

Zeno Rocha
  • 3,226
  • 1
  • 23
  • 27
victor
  • 57
  • 9
  • 4
    Possible duplicate of [Copy to clipboard without Flash](http://stackoverflow.com/questions/6355300/copy-to-clipboard-without-flash) – blm Oct 22 '15 at 17:25
  • https://github.com/zeroclipboard/jquery.zeroclipboard – epascarello Oct 22 '15 at 17:27
  • @victor Trust that users are voting based on the contents of your post, which they can only know after reading. Voting to close is a privilege earned after contributing to the site for some time; these users are essentially trusted to make the right decision when a question has been asked and answered elsewhere before; there's no need to add that disclaimer in bold to your question. – TylerH Oct 22 '15 at 19:20

1 Answers1

2

Sorry, here's a working solution. Just change your class from "container" to "c" or anything else to match the $('.c') selector below (container is a class used by Bootstrap, which is a very popular library). When you click one of the DIVs, the text will be selected and copied to the clipboard. Older browsers won't work, BTW.

$(function() {
    $('.c').on('click', function () {
        SelectText($(this)[0]);
        document.execCommand('copy');
    });

    function SelectText(element) {
        var doc = document, range, selection;
        if (doc.body.createTextRange) {
            range = document.body.createTextRange();
            range.moveToElementText(element);
            range.select();
        } else if (window.getSelection) {
            selection = window.getSelection();
            range = document.createRange();
            range.selectNodeContents(element);
            selection.removeAllRanges();
            selection.addRange(range);
        }
    }
});
Todd Sprang
  • 2,899
  • 2
  • 23
  • 40