Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire event with right mouse click and Paste

I want to fire an event in a textarea immediately after paste some text inside the textarea. I can do that when Shift+Ins is used; however, I cannot do it when right mouse button and then paste (from the drop down menu) is chosen. Keyup fires after Shift+Ins. None of the rest fires when Paste is chosen after right mouse button clicking... What do I have to do?

<textarea name="message"  id="message"></textarea>

$("#message").on('keyup contextmenu', function(event) { 
     alert("ok");
 });

http://jsfiddle.net/f29vuwoL/7/

Thank you

like image 244
Unknown developer Avatar asked Oct 25 '25 00:10

Unknown developer


1 Answers

Most browsers support the input event, which is fired when something is pasted or otherwise added, regardless of how:

$("#message").on('keyup contextmenu input', function(event) { 
  alert("ok");
});

Updated Fiddle

Note that using input is the most general method, firing when the control gets input regardless of how, and so if you hook multiple events (as above), you'll get multiple calls for the same input. For instance, if you hook both keyup and input, on browsers that support input, you'll get two calls. Similarly for paste and input when the user pastes, on browsers that support both.

If you need to support browsers that don't have either input or paste, I'm afraid the unfortunate answer is that you need to poll. Still, polling every (say) 250ms isn't asking the browser to do that much work, and you can feature-detect whether it's necessary:

var message = $("#message");
var events = null;
var previous;
if ('oninput' in message[0]) {
    // Browser supports input event
    events = "input";
} else if ('onpaste' in message[0]) {
    // Browser supports paste event
    events = "paste keyup contextmenu";
}
if (!events) {
    // Ugh, poll and fire our own
    events = "pseudoinput";
    previous = message.val();
    setInterval(function() {
        var current = message.val();
        if (current != previous) {
            previous = current;
            message.trigger(events);
        }
    }, 250);
}
console.log("Using: " + events);
message.on(events, function(e) { 
  console.log("Got event: " + e.type);
});

Updated Fiddle

like image 176
T.J. Crowder Avatar answered Oct 26 '25 13:10

T.J. Crowder