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.
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.
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.
<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.
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.
You will never know for sure. Even when intercepting key input, the use may have used the context menu to paste using the mouse. Accessing the clipboard (to compare the input with the clipboard contents) will not work the way you want because it is a strict user-only operation. You are not able to access is programmatically without the explicit consent of the user (the browser will show a confirmation message).
I know for textarea you can capture on paste event using the onPaste
event.
HTML:
<textarea id="textEditor" />
In JS:
var editor = document.getElementById("textEditor");
if (isIE /* determine this yourself */) {
editor.onPaste = function() {
}
} else {
//Not IE
editor.onpaste = function() {
}
}
//The capitalisation of the onpaste (non-IE) and onPaste (IE) makes a difference.
As for typing, there's onKeyDown
, onKeyUp
, onKeyPress
events.
Hope this helps.
Possible SO-related question IE onPaste event using javascript not HTML