Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I know user is typing or pasting?

In text fields of my JSP, I wish to know whether user is typing in the data or just pasting. How can I identify this using javascript ?

EDIT: As per Andy's answer I know how I can go about it, but still curios how those guys wrote onpaste event.

like image 338
Ravi Gupta Avatar asked Dec 28 '22 23:12

Ravi Gupta


2 Answers

Safari, Chrome, Firefox and Internet Explorer all support the onpaste event (not sure about Opera). Latch onto the onpaste event and you will be able to catch whenever something is pasted.


Writing this is simple enough. Add the event handler to your input using html:
<input type="text" id="myinput" onpaste="handlePaste(event);">

or JavaScript-DOM:

var myInput = document.getElementById("myInput");

if ("onpaste" in myInput) // onpaste event is supported
{
    myInput.onpaste = function (e)
    {
        var event = e || window.event;
        alert("User pasted");
    }
}
// Check for mutation event support instead
else if(document.implementation.hasFeature('MutationEvents','2.0'))
{
    /* You could handle the DOMAttrModified event here, checking 
       new value length vs old value length but it wouldn't be 100% reliable */
}

From what I've read, Opera does not support the onpaste event. You could use the DOMAtrrModified event, but this would fire even when scripts change the value of the input box so you have to be careful with it. Unfortunately, I'm not familiar with mutation events so I wouldn't like to mess this answer up by writing an example that I wouldn't be confident of.

like image 174
Andy E Avatar answered Dec 31 '22 14:12

Andy E


Count the key presses and make sure it matches whats in the text box a paste will not have complete number of characters as is in the text box.

like image 45
Paul Whelan Avatar answered Dec 31 '22 14:12

Paul Whelan