Search code examples
jqueryevent-handlingstoppropagation

Preventing keyUp event if the user pastes something in a textarea


If the user types someting in the textarea#q, the do_domething() function is called. If the user pastes the text instead of typing it, the do_something() function should be avoided. Any ideas? This is my current code:

$('#q').keyup(function(e){
    do_something();
}).bind('paste',function(event) {
    //user pasted text, there is not need to do_something();
    //tried both of these approaches, none worked out.
    event.stopPropagation();
    event.stopImmediatePropagation();
});

Solution

  • If a user right clicks and uses the context menu to paste into the textarea then you are good. That leaves the issue of the user using "Ctrl + P" to paste into the textarea. You could try capturing the keycodes and skipping the function when the key combo is pressed. Try this:

    On keydown:
    
    var isCtrl = false;
    
    $('#q').keydown(function (event) {
        if(e.keycode == 17)
            isCtrl = true;
        if(isCtrl == false)
            do_something();
    });
    
    $('#q').keyup(function (e) {
        isCtrl = false;
    });
    

    So the idea is to capture the "Ctrl" key. If they press it you don't want to fire the function. In order to paste "Ctrl + P", the "Ctrl" key must be pressed therefore "isCtrl" would be true preventing the firing of the do_something(); function. The only exception to this would be using sticky keys in windows where "Ctrl" doesn't have to be held when you type "p".

    This all is assuming of course that it is alright if you fire your function in the keydown event rather than in the keyup. Depending on your function this may not be appropriate.

    Hope this works.