0

I want to catch event when some text added into a textarea by copy paste or programmatically so i can add some work about it.

How do i do that? Which jquery method should i use for that? Change method didn' t work.

$('textarea').on('change', function(){
--do some stuff;
});
lowdegeneration
  • 195
  • 1
  • 11
  • Possible duplicate of [JavaScript get clipboard data on paste event (Cross browser)](http://stackoverflow.com/questions/2176861/javascript-get-clipboard-data-on-paste-event-cross-browser) – Michał Kutra Feb 28 '16 at 12:17

3 Answers3

1

You can use input event to handle pasting done by users,

$('textarea').on('input', function(){
--do some stuff;
});

But this event will not be fired if you do it by programmatically.

Rajaprabhu Aravindasamy
  • 63,064
  • 13
  • 90
  • 119
1

...by copy paste...

The copy/paste bit is easy on a modern browser: Catch the input event.

...or programmatically...

There's no event raised when the value of a textarea is changed programmatically. The only way is to use a MutationObserver watching for subtree, childList, and characterData changes. MutationObserver is well supported other than in IE, where it didn't arrive until IE11. However, for most purposes, you can use a polyfill that uses the obsolete "mutation events" to provide a barebones MutationObserver shim. Just search for "MutationObserver polyfill" or "MutationObserver shim" to find options.

To my surprise, setting the value of a textarea does not fire a MutationObserver on Chrome (some other things do, but not that). This means that in order to detect programmatic changes, you'll have to poll (blech!), keeping the old value and periodically (say, every 20-100ms) checking to see if it's different.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
1

There is always the paste event that you can intercept.

Below is an example

var yourElement = document.getElementById("yourElementId");

yourElement.addEventListener('paste', function(event) {
    console.log("The data that was just pasted was "+event.clipboardData.getData('text/plain'));
});

Try it on the search bar at the right of the nav bar on StackOverflow in your browser, and see for yourself.

You can get a reference to it using

document.getElementsByName("q")[0]
kkaosninja
  • 1,201
  • 10
  • 21