Textarea OnClick Selection and Copy

A textarea can select all of its contents when the user clicks it. The original plus2net copy facility is preserved, but the modern Clipboard API is preferred over the deprecated document.execCommand("copy").

const textArea = document.getElementById('t1');
textArea.select();
await navigator.clipboard.writeText(textArea.value);

Demo of onclick selection and copy inside textarea

Table of Contents

Complete Working Source Top ↑

<textarea id="t1" rows="4" cols="35">This text can be selected and copied.</textarea>
<p id="my_msg" aria-live="polite"></p>
<script>
const textArea = document.getElementById('t1');
const message = document.getElementById('my_msg');
textArea.addEventListener('click', async () => {
  textArea.focus();
  textArea.select();
  try {
    await navigator.clipboard.writeText(textArea.value);
    message.textContent = 'Text copied. Paste it where required.';
  } catch (error) {
    message.textContent = 'Text selected. Use Ctrl+C or Command+C to copy.';
  }
});
</script>

Using mouseup Instead of click Top ↑

The original page also demonstrated selecting the textarea from a mouseup handler. That remains possible:

const textArea = document.getElementById('t1');
textArea.addEventListener('mouseup', () => {
  textArea.select();
});

Clipboard Permissions and Fallback Top ↑

navigator.clipboard.writeText() normally requires a secure HTTPS context and user activation. If clipboard access is unavailable, keep the text selected and tell the user to copy manually rather than silently removing the copy facility.

Event Handling onKeyPress Mouse event




Subscribe to our YouTube Channel here



plus2net.com







Bilal

01-04-2013

I want to get this functionality on focus event of textarea instead of click event.



✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer