JJSO
JJSO

Reputation: 61

How to determine if an onChange event was called by an onPaste

I have a Javascript function that is associated with an onChange event. I understand that some browsers support onPaste at either the document or an element level. Is there a way to determine if the onChange event was caused by a "paste" - I tried adding a global var that gets set when onPaste is fired, and then reset it at the end of my onChange routine, but there is no guarantee that the onPaste function gets called before the onChange.

Upvotes: 6

Views: 8170

Answers (5)

shivamm
shivamm

Reputation: 11

In case you don't want to trigger onChange event when onPaste is triggered... try event.preventDefault()

Upvotes: 0

bobpoekert
bobpoekert

Reputation: 1014

Every time you see an onchange event compare the current length of the value of the field to the previous length, and the current time to the previous time. If the characters were entered faster than a person could conceivably type them, they must have been pasted.

Upvotes: 0

Raphael Michel
Raphael Michel

Reputation: 854

You could use onKeyPress/onKeyUp/onKeyDown/onPaste instead of onChange.

Upvotes: 1

Shadow Wizzard
Shadow Wizzard

Reputation: 66388

This worked fine for me:

<input type="text" onchange="ValueChanged(event, this);" onpaste="this.setAttribute('pasted', '1');"/>


<script type="text/javascript">
function ValueChanged(evt, sender) {
    var blnCameFromPaste = ((sender.getAttribute("pasted") || "") == "1");
    if (blnCameFromPaste)
        alert("changed by paste");
    else
        alert("changed without paste");
    sender.setAttribute("pasted", "0")
}
</script>

Upvotes: 1

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114417

I don't think you'll be able to do this universally. See the current state of testing this feature.

One way to detect a paste would be to count the time between "keypresses" once a field has focus.

Upvotes: 0

Related Questions