Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
80
rated 0 times [  81] [ 1]  / answers: 1 / hits: 57504  / 14 Years ago, fri, july 9, 2010, 12:00:00

Using JavaScript how do you to detect what text the user pastes into a textarea?


More From » javascript

 Answers
26

You could use the paste event to detect the paste in most browsers (notably not Firefox 2 though). When you handle the paste event, record the current selection, and then set a brief timer that calls a function after the paste has completed. This function can then compare lengths and to know where to look for the pasted content. Something like the following. For the sake of brevity, the function that gets the textarea selection does not work in IE. See here for something that does: How to get the start and end points of selection in text area?



function getTextAreaSelection(textarea) {
var start = textarea.selectionStart, end = textarea.selectionEnd;
return {
start: start,
end: end,
length: end - start,
text: textarea.value.slice(start, end)
};
}

function detectPaste(textarea, callback) {
textarea.onpaste = function() {
var sel = getTextAreaSelection(textarea);
var initialLength = textarea.value.length;
window.setTimeout(function() {
var val = textarea.value;
var pastedTextLength = val.length - (initialLength - sel.length);
var end = sel.start + pastedTextLength;
callback({
start: sel.start,
end: end,
length: pastedTextLength,
text: val.slice(sel.start, end)
});
}, 1);
};
}

var textarea = document.getElementById(your_textarea);
detectPaste(textarea, function(pasteInfo) {
alert(pasteInfo.text);
// pasteInfo also has properties for the start and end character
// index and length of the pasted text
});

[#96293] Tuesday, July 6, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
amari

Total Points: 736
Total Questions: 111
Total Answers: 90

Location: Saint Pierre and Miquelon
Member since Fri, Jan 28, 2022
2 Years ago
;