Monday, April 30, 2018

Copying data to memory with Javascript and jQuery

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 thigs such as Ids, phone numbers, urls or connection strings. Stuff that's complicated to type or very error prone.

Such a simple solution can be achieved using javascript and jQuery.

My 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=""

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:

Hope it helps!