Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript copy element to clipboard with all styles

I am trying to copy a div to the clipboard. The div has a few styles, including a background. I have made a script to copy the div to the clipboard, but I can't figure out how to do the background.

I have seen this done, but I can't remember how.

Any help would be appreciated.


This is as far as I got:

function executeCopy(text) {
    var copyDiv = document.createElement('div');
    copyDiv.contentEditable = true;
    document.body.appendChild(copyDiv);
    copyDiv.innerHTML = text;
    copyDiv.unselectable = "off";
    copyDiv.focus();
    document.execCommand('SelectAll');
    document.execCommand("Copy", false, null);
    document.body.removeChild(copyDiv);
}
#foo {
  background-color: red;
  font-family: cursive;
}
<div id="foo">Test</div>
<button onclick="executeCopy(document.getElementById('foo').innerHTML);">Copy</button>
like image 297
asportnoy Avatar asked Feb 01 '18 01:02

asportnoy


1 Answers

You can try the following fiddle. It works with every text style there is and it's interoperable with MS Word and Pages (I just tested it).

The code is pretty straightforward so I wouldn't really get into the depths of it, but feel free to drop me any questions should you feel like. :)

const copyWithStyle = ( element ) => {

    const doc = document;
    const text = doc.getElementById( element );
    let range;
    let selection;

    if( doc.body.createTextRange ) {

        range = doc.body.createTextRange();
        range.moveToElement( text );
        range.select();

    } else if ( window.getSelection ) {

        selection = window.getSelection();

        range = doc.createRange();
        range.selectNodeContents( text );

        selection.removeAllRanges();
        selection.addRange( range );

    }

    document.execCommand( 'copy' );
    window.getSelection().removeAllRanges();
    document.getElementById( 'clickMe' ).value = 'Copied to clipboard!';

}

https://jsfiddle.net/aypdg3kL/

From the example in JSFiddle

HTML

<div id="text" style="color:red">
    <i>Hello</i> world!
</div>
<input id="btn" onclick="CopyToClipboard('text')" type="button" value="Copy" />

JS

function CopyToClipboard(element) {

        var doc = document
        , text = doc.getElementById(element)
        , range, selection;
    
    if (doc.body.createTextRange)
    {
        range = doc.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } 
    
    else if (window.getSelection)
    {
        selection = window.getSelection();        
        range = doc.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
    document.execCommand('copy');
    window.getSelection().removeAllRanges();
    document.getElementById("btn").value="Copied";
}
like image 119
weirdpanda Avatar answered Nov 15 '22 14:11

weirdpanda