Skip to content

How to handle paste event in textarea HTML element?

In this post, we will learn how to handle paste event properly in a textarea HTML element. Textarea provides a onpaste event by default but it doesn’t work the way you expect it to be.

onpaste event is triggered once you paste the text. When you try to retrieve the value from the textarea using textarea.value you will always retrieve the current text on the textarea field and not the one you pasted. This is because the onpaste event is triggered once you pressed Ctrl + V and not after you pasted the text. Hence this need to handled differently by getting the text value from the clipboard.

<textarea id="textarea" placeholder="Paste your string here.." onpaste = "handlePaste()"></textarea>

In JavaScript..

var ta = document.getElementById("textarea");
ta.onpaste = handlePaste;

You can get the pasted text using the clipboard APIs and write your logic to handle the pasted text.

function handlePaste(event) {
			let pastedText = (event.clipboardData || window.clipboardData).getData('text');
 			alert('Pasted!\n' + pastedText);
			//Your logic to handle pasted text
See also  Creating a reusable button component in React

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.