jQuery.copy()


Copy text and information to the clipboard.

jQuery.copy()Returns: Boolean

Description: Copies selected data to clipboard.

This is functionally identical to using document.execCommand or simply pressing Ctrl + C, but with some extra featured in case document.execCommand fails. Upon a successful execution, this function will return true.

Consider the following example:

1
2
3
4
5
6
7
<div>
<p class="copy">Some text to copy</p>
</div>

<script>
$( ".copy" ).select();
</script>

The paragraph with the class "copy" will be selected. From there, we can call the copy function.

1
$.copy();

The text "Some text to copy" will be copied to the clipboard. This process will work as if you copied by right-clicking or by using keyboard shortcuts, but will not invote a copying event listener.

jQuery.copy( String )Returns: Boolean

Description: Copies strings to clipboard.

This is function works similarly to the window.copy which is availible in the console of some browsers. A string that is imputed into this function will be copied to the clipboard. Upon a successful execution, this function will return true.

Consider a page with a simple list on it:

1
2
3
var str = "Copied!";

$.copy( str );

The text "Copied!" will be copied to the clipboard. This process will not invoke a copying event listener.

If the Data passed into $.copy is not already a string, it will become one if its .toString() function returns a usable string. Otherwise, the function will copy a jsonified string of the parameter.

1
2
3
4
5
6
7
8
9
10
11
<div>Hello World</div>

<script>
$.copy( 1234 ) // "1234" is copied
$.copy( false ) // "false" is copied
$.copy( {hello: "world"} ) // '{"hello":"world"}' is copied
$.copy( new Date("1/1/2021") ) // "2021-01-01T05:00:00.000Z" is copied
$.copy( document.querySelector("div") ) // "<div>Hello World</div>" is copied
$.copy( 12345678901234567890n ) // "12345678901234567890" is copied
$.copy( {toString: function(){return "Hello World"} ) // "Hello World" is copied
</script>

Note: the .toString() function will only trigger if its output is not the literal "[object Object]". If this is the case, the passed data will be jsonified and then copied.