Monday, April 30, 2018

Copying data to memory with JavaScript and jQuery

How to copying data to memory with JavaScript and jQuery? Read and understand.

A nice feature to have in your site is the ability of letting users copy certain pieces of data to the memory. This is useful for example to copying things such as Ids, phone numbers, urls or connection strings. Stuff that's complicated to type or very error prone.

Turns out that a simple solution can be achieved using JavaScript and jQuery. Let's see how.

A Simpler Approach

Here's how I approached it:

1. add a class to show a copy icon whenever you hover a DOM element:

Ex. class="icon-clipboard"

2. add a css class to identify what you want to copy:

Ex. class="copyableTemplate"

3. add the data to copy using the "data-clipboard" attribute:

Ex. data-clipboard="http://lipsum.com/"

4. handle the click event on the copy icon and get the data associated to it:

Ex. $('body').on('click', 'div.icon-clipboard', function() { })

5. copy to memory using the browser's api:

Ex. document.execCommand('copy');

Source Code:


See Also

About the Author

Bruno Hildenbrand      
Principal Architect, HildenCo Solutions.