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
<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>
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();
});
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
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| Bilal | 01-04-2013 |
| I want to get this functionality on focus event of textarea instead of click event. | |