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 mand, 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 binations. 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!
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 mand, 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 binations. 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!
Share Improve this question asked Jul 16, 2012 at 19:33 DoubleTroubleDoubleTrouble 9022 gold badges8 silver badges21 bronze badges 2- attach a keydown event to the actual textarea. You're attaching it to the whole page. – Marc B Commented Jul 16, 2012 at 19:36
-
Both answers below are good, so no need for an almost identical third one, just your code can be modified for example also to
document.onkeydown = function(event){alert("Test" + event.target);};
to be functional. But undoubtedly better to attach an event handler directly to textarea. – Stano Commented Jul 16, 2012 at 19:52
3 Answers
Reset to default 6I 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/dom/events/keys.html
Basically, you'd want something like this:
document.getElementById('content').addEventListener('keydown', function (e){
// Do your key bination detection
}, false);
MDN on events. Probably more helpful
var textarea = document.getElementById('textarea');
textarea.onkeydown = function ()
{
alert("Test");
};
Using jQuery (delegate).
$("body").delegate("textarea", "keydown",function(e){
alert("Test");
//code logic goes here
//if(e.which == 13){
//Enter key down
}
});
Or
$('textarea').live("keydown", function(e) {
alert("Test");
// e.which is which key, e.g. 13 == enter
});
Docs on live. Docs on event.
document.querySelector('textarea') // find a DOM element (by tag name at this case)
.addEventListener('keydown', // bind an event listener for "keydown" event
e => { // declare a callback function when that event happens
console.log(e.target.value) // print the target node value (<Textarea>)
})
<textarea></textarea>