Search code examples
javascriptjqueryclipboardzeroclipboardclipboard.js

How to copy a div's content with clipboard.js or zeroclipboard?


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?


Solution

  • 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);
            }
        }
    });