html span id as javascript function argument

2.5k Views Asked by At

I'm trying to create a copy to clipboard IE javascript function but my code isn't working. How should I format my parameters and pass the argument?

/*invisible storage*/
<textarea id="storageBox" STYLE="display:none;">
</textarea>

<p id="abc">I WANT TO COPY THIS TEXT</p>

<button onClick="Copy(abc);">Copy</button><br />

<script type="text/javascript">
function Copy(txt) {
storageBox.innerText = txt.innerText;
Copied = storageBox.createTextRange();
Copied.execCommand("RemoveFormat");
Copied.execCommand("Copy");
}
</script>

Major karma for anyone who can write this using zclip or show me a similar example as well!!

3

There are 3 best solutions below

2
On BEST ANSWER

The following changes should help:

... onclick="Copy('abc');"...

storageBox.value = document.getElementById(txt).innerText

I think. You weren't very specific in saying what doesn't work or even for what reason you're trying to hijack the clipboard (what if the user has important stuff in there?)

2
On

First, you need to pass the parameter as a string:

<button onClick="Copy('abc');">Copy</button><br />

In your function, you need to get the element from the DOM based on this ID (as a string):

function Copy(txt) {
   storageBox.innerText = document.getElementById(txt).innerText;
   ...
2
On

Though I commented your script working fine, there is something to fix in the HTML. If you set display: none, execCommand() can't copy the content. So you'll need to do this:

<textarea id="storageBox" style="width: 0px; height: 0px; border: 0px;"></textarea>