I see that when I try to read the value from a textarea field when its onpaste
function is called, I get the old value of the field (the one before the paste operation), not the new value (the one after the paste operation).
Here is a demonstration of this behaviour: http://jsfiddle.net/qsDnr/
A copy of the code follows:
<!DOCTYPE html>
<html>
<head>
<title>On Paste</title>
<script type="text/javascript">
var textareaElement;
var previewElement;
function update()
{
previewElement.innerHTML = textareaElement.value;
}
window.onload = function() {
textareaElement = document.getElementById('textarea');
previewElement = document.getElementById('preview');
textareaElement.onpaste = update
}
</script>
</head>
<body>
<textarea id="textarea">
</textarea>
<div id="preview">
</div>
</body>
</html>
You can confirm the behaviour with the following steps.
foo
to your clipboard.foo
appears in the div element.Since I want the div element to always show what was updated in the textarea element with the paste operation, the desired output is foo
and foo foo
in step 2 and step 3 respectively.
One way I have managed to get the desired output is by delaying the update()
function call with window.setTimeout()
, so instead of
textareaElement.onpaste = update
I have got
textareaElement.onpaste = function() {
window.setTimeout(update, 100);
};
this time (demo: http://jsfiddle.net/cwpLS/). This does what I want. However, this feels more like a workaround rather than a straightforward way of doing what I want. I would like to know if there is any alternate or better way to do this.
I'm pretty sure that you setTimeout solution is the only way to achieve the desired effect, or try to access the clipboard object - which can get messy if you're going for cross-browser & old browser support.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With