Copy to clipboard using javascript without any plugin

Copy to clipboard using javascript, this is the topic that we are going to explore in this post. The solution we will discuss here will use native javascript and no third party tool. As the solution is bare minimum code snippet, it’s browser support will be limited.

The way this solution for Copy to clipboard using javascript works is simple and is divided in 3 steps

  1. Select the text from DOM element
  2. Create an input element and place the selected text as value of created input.
  3. Focus on created input element and select the entire text (It’s value).
  4. Execute (document.execCommand(‘copy’)

Let’s begin with our solution

Select the text to be copied

<p id="selectedItem">Text to copy</p> 
<button onClick="copyT('selectedItem')">Copy</button>

The remaining steps are summed up in following function

function copyT(objId) {
    //Step 1: select the text from DOM element
    var txt = document.getElementById(objId).textContent;

    //Step 2: Create input and set value
    var elem = document.createElement('input');
    elem.value = txt;

    //position is set such that the element is not visible
    elem.style = 'postion:relative;top:-100px;';

    //append the input element to body
    document.body.appendChild(elem);

    //set focus to inserted input element
    elem.focus();

    //Step 4: Select the text in input element
    elem.setSelectionRange(0, txt.length);
    //Step 4: Execute document.execCommand('copy')
    if (document.execCommand('copy')) {
        alert('Copied successfully');
    } else {
        alert('Clipboard access not supported in this browser');
    }
}

There are few pitfalls to this soulution. It will not work in the browser that have disabled access to clipboard using javascript (like Safari). In that case, above solution will simply alert the message “Clipboard access not supported in this browser”

Leave a Reply

Your email address will not be published. Required fields are marked *