Jump to content

I need to replace textarea for text in a "Copy to Clipboard" script

Dr Pepper Can

Recommended Posts

JMRKER was kind enough to improvise this solution below. However, although I need to have information (text) copied to the clipboard, I need NOT to have it in a textarea. It shouldn't be available for modification.
Isn't there a way to keep this text data in the code, and then transferring it to the clipboard when a button is clicked?

Thanks guys :)


<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" /> <title> HTML5 page </title>
<!-- From: https://stackoverflow.com/questions/6300213/copy-selected-text-to-the-clipboard-without-using-flash-must-be-cross-browser -->
   <style> </style>

<textarea id="textarea" rows="6" cols="40">
    Lorem ipsum dolor sit amet, eamsemper maiestatis no.
<button id="copyTAreaBlock">Click to copy</button>
<span id="copyTAreaAnswer"></span>
<p> <input type="text" id="textInput"><br/>
<button id="copyText">Click to copy</button>
<span id="copyTextAnswer"></span>

<script> // Setup the variables for TEXTAREA
var textarea = document.getElementById("textarea");
var answer = document.getElementById("copyTAreaAnswer");
var copyTArea = document.getElementById("copyTAreaBlock");

copyTArea.addEventListener('click', function(e) {
// Select some text (you could also create a range) textarea.select();
// Use try & catch for unsupported browser try {
// The important part (copy selected text)
var ok = document.execCommand('copy');

if (ok) answer.innerHTML = 'Copied!';
else answer.innerHTML = 'Unable to copy!';
} catch (err) {
answer.innerHTML = 'Unsupported Browser!'; } });



Link to comment
Share on other sites

The easiest solution would be to set the textarea to readonly by giving it a readonly attribute. You can style it to not look like a text area by giving it a transparent background and no border.

If you actually want to copy text from an element that's not a textarea I would actually have to do some tests to see what the browsers do and don't allow.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...