PDA

View Full Version : Instant Text copy button



npsari
05-03-2007, 12:49 PM
The below script allows text copy in a click of a button:
Try it out, it is nice actually



<script type="text/javascript">
function cmdA(el) {
with(el){
focus();
select();
}
if(document.all){
txt=el.createTextRange()
txt.execCommand("Copy")
window.status='Selected and Copied to Clipboard!'
document.WordForm.cpyButton.value="Copied!";
setTimeout("WordForm.cpyButton.value='Copy'",1000)
}
else window.status='Press Ctrl-C to Copy the Text to the Clipboard'
setTimeout("window.status='WebTv users you must Press Cmd & C !'",3000)
}
</script>


<form name="WordForm" >
<input type="text" id="Editbox1" size="30" name="Screen" value="This text should be copied">
<input type="button" width="120" NAME="cpyButton" value="Copy" onClick="cmdA(document.WordForm.Screen)">

However, when the button is clicked, another button shows with the word copied!

Can someone show me how can the script display an image (/images/copied.gif) instead of the button.

Your support is appreciated
npsari

Twey
05-03-2007, 01:25 PM
Try it out, it is nice actuallyNot really... it uses a lot of bad coding practices. Try this (should be a drop-in replacement for the above function):
<script type="text/javascript">
function cmdA(el) {
var txt,
b = document.forms['WordForm'].elements['cpyButton'],
g = document.images['cpyImage'];

if(!g) {
g = document.createElement("img");
g.id = "cpyImage";
g.src = "/images/copied.gif";
g.style.display = "none";
b.parentNode.insertBefore(document.createElement("img"), b);
}

el.focus();
el.select();

if(
txt = el.createTextRange &&
txt = txt() &&
txt = txt.execCommand &&
txt("Copy")
) {
b.style.display = "none";
g.style.display = "";
setTimeout(
(function(b, g) {
return function() {
b.display = "";
g.display = "none";
b = g = null;
};
)(b.style, g.style),
1000
);
} else {
b.style.display = "none";
b.parentNode.insertBefore(document.createTextNode("Unable to copy. Please press Ctrl+C, Cmd+C, or your system's shortcut."), b);
b.parentNode.removeChild(b);
}
txt = b = g = null;
}
</script>

npsari
05-03-2007, 01:33 PM
I tried it many ways,

it always give me an error page

how should I place it in my code

Show me plz if could

Twey
05-03-2007, 07:21 PM
If you show me the page you've tried to put it in, yes. It's also possible that there's a bug with my code.