I am trying to check the length of the text in a textarea when someone pastes content in there via the right-click but can't seem to find how to do it.
Asked
Active
Viewed 4,090 times
1 Answers
17
$('textarea').bind('paste', function() {
var that = this;
setTimeout(function() {
var length = that.value.length;
alert(length);
}, 0);
});
Live demo: http://jsfiddle.net/4UrE3/1/
Works in Firefox 3.6, Chrome, Safari and IE9 beta. Does not work in Opera.

Šime Vidas
- 182,163
- 62
- 281
- 385
-
@Sime: Why do you have a `setTimeout` in the function? – gen_Eric Feb 08 '11 at 00:33
-
8@Rocket Because (in browsers) the pasted text appears in the text-box only after the paste handler has finished. Inside the paste handler, the text-box is still empty. See here: http://jsfiddle.net/4UrE3/3/ `setTimeout(function() { ... }, 0);` will execute the function immediately after the paste handler has returned and the text-box has been populated, ergo, it is safe to read the `this.value` property. – Šime Vidas Feb 08 '11 at 00:42
-
@Sime: So, that's why `.bind('paste')` wasn't working before, thanks! – gen_Eric Feb 08 '11 at 00:46
-
@Rocket Yes, I guess that's why :) – Šime Vidas Feb 08 '11 at 00:51
-
This above Fiddler works on Firefox & IE11& CHrome! :) – Zeek2 Feb 24 '17 at 14:45
-
@ŠimeVidas, but the 'paste' event is not exclusive to context menu. It will also get triggered when the user presses Ctrl+V or Cmd+V. I'm thinking if there's a way to segregate these two actions (keyboard paste and contextmenu paste). – mvvijesh Apr 27 '20 at 08:18
-
@mvvijesh - ```$('.foo').on('input paste', function() { ... });``` – WiiLF Jan 18 '23 at 17:26