copy text to clipboard with browser javascript

As of 2016, you can now copy text to the clipboard in most browsers because most browsers have the ability to programmatically copy a selection of text to the clipboard using document.execCommand(“copy") that works off a selection.

As with some other actions in a browser (like opening a new window), the copy to clipboard can only be done via a specific user action (like a mouse click). For example, it cannot be done via a timer.

Here’s a code example:
document.getElementById(“copyButton").addEventListener(“click", function() {

function copyToClipboard(elem) {
// create hidden text element, if it doesn’t already exist
var targetId = “_hiddenCopyText_";
var isInput = elem.tagName === “INPUT" || elem.tagName === “TEXTAREA";
var origSelectionStart, origSelectionEnd;
if (isInput) {
// can just use the original source element for the selection and copy
target = elem;
origSelectionStart = elem.selectionStart;
origSelectionEnd = elem.selectionEnd;
} else {
// must use a temporary form element for the selection and copy
target = document.getElementById(targetId);
if (!target) {
var target = document.createElement(“textarea"); = “absolute"; = “-9999px"; = “0″; = targetId;
target.textContent = elem.textContent;
// select the content
var currentFocus = document.activeElement;
target.setSelectionRange(0, target.value.length);

// copy the selection
var succeed;
try {
succeed = document.execCommand(“copy");
} catch(e) {
succeed = false;
// restore original focus
if (currentFocus && typeof currentFocus.focus === “function") {

if (isInput) {
// restore prior selection
elem.setSelectionRange(origSelectionStart, origSelectionEnd);
} else {
// clear temporary content
target.textContent = “";
return succeed;
source url:

It works on new browsers such as firefox, opera, chrome, internet explorer etc.
Tested using samsung note 3 browsers such as firefox, chrome, opera, safari/default.

Looks like I have to recode to add this copy function to cell phone.

Styling input buttons for iPad and iPhone

Tested to find the Safari, the browser of iphone and ipad has a different rendering algorithm for styling the webpage in particular for the button.

I tested all button styling in css works for desktop browser and even for my android phone with various browsers like Chrome, Opera etc.

Iphone or Ipad ignores the stylesheet for button unless you use the following code:

-webkit-appearance: none;

or say,

input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;