6

I got the following code from Intercept paste event in Javascript.

I need to get it before it is pasted, otherwise i lose the "\n" characters i need to save.

It works great to intercept clipboard data for one element with an id. I need it to work on all input elements. When I try to use jQuery to get the input elements nothing.

Any help is appreciated.

var paster = function () {
    var myElement = document.getElementByTagName('pasteElement');
    myElement.onpaste = function(e) {
        var pastedText = undefined;
        if (window.clipboardData && window.clipboardData.getData) { // IE
            pastedText = window.clipboardData.getData('Text');
        } else if (e.clipboardData && e.clipboardData.getData) {
            pastedText = e.clipboardData.getData('text/plain');
        }
        processExcel(pastedText); // Process and handle text...
        return false; // Prevent the default handler from running.
    };
}
3
  • 2
    there is no jquery in there. that's just plain javascript... Commented Jul 2, 2014 at 20:50
  • Correct. I'm willing to do it either way. Commented Jul 2, 2014 at 20:51
  • 1
    so show your jquery code. we are not here to bang out a solution for you. Commented Jul 2, 2014 at 20:52

2 Answers 2

13

Just add a paste event listener to the document.

document.addEventListener("paste", function (e) {
    console.log(e.target.id);
    var pastedText = undefined;
    if (window.clipboardData && window.clipboardData.getData) { // IE
        pastedText = window.clipboardData.getData('Text');
    } else if (e.clipboardData && e.clipboardData.getData) {
        pastedText = e.clipboardData.getData('text/plain');
    }
    e.preventDefault();
    e.target.value = "You just pasted '" + pastedText + "'";
    return false;
});

fiddle

Sign up to request clarification or add additional context in comments.

Comments

3

What nmaier said, but you also need to check for the original event.

document.addEventListener("paste", function (e) {
    console.log(e.target.id);
    var pastedText = undefined;
    if (window.clipboardData && window.clipboardData.getData) { // IE
        pastedText = window.clipboardData.getData('Text');
    } else {
        var clipboardData = (e.originalEvent || e).clipboardData;
        if (clipboardData && clipboardData.getData) {
            pastedText = clipboardData.getData('text/plain');
        }
        e.preventDefault();
        e.target.value = "You just pasted '" + pastedText + "'";
        return false;
    }
});

Also, you should probably add the event listener just to the element, instead of the whole document.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.