Search code examples
javascriptgreasemonkey

How to use keydown event in textarea?


I am not very used to using javascript but I have gotten sick of manually repeating a tast at work. When I write in a discussion forum I need a quick short command, like Ctrl-Alt-z, to insert some text into a textarea object.

I have already written a function that inserts the text at the text cursor insertAtCursor(text). The ID of the textarea is "content".

I know how to solve the problem of checking for key combinations. The problem I have is basically to check for any keyboard input at all.

I have tried the following:

document.keydown(function(event){
  alert("Test");
});

However, it does not work.

Thanks in advance!


Solution

  • I think you're going to have a tough time if you're looking for cross-browser solutions. Here's something to help you: http://www.quirksmode.org/dom/events/keys.html

    Basically, you'd want something like this:

    document.getElementById('content').addEventListener('keydown', function (e){
        // Do your key combination detection
    }, false);
    

    MDN on events. Probably more helpful