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() {
copyToClipboard(document.getElementById(“copyTarget"));
});

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");
target.style.position = “absolute";
target.style.left = “-9999px";
target.style.top = “0″;
target.id = targetId;
document.body.appendChild(target);
}
target.textContent = elem.textContent;
}
// select the content
var currentFocus = document.activeElement;
target.focus();
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") {
currentFocus.focus();
}

if (isInput) {
// restore prior selection
elem.setSelectionRange(origSelectionStart, origSelectionEnd);
} else {
// clear temporary content
target.textContent = “";
}
return succeed;
}
source url:http://stackoverflow.com/questions/22581345/click-button-copy-to-clipboard-using-jquery

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;
}

source: http://stackoverflow.com/questions/5449412/styling-input-buttons-for-ipad-and-iphone