0

I have this function, it should track ctrk+enter keys and send message. But function don't work. But if i call HotKeys(); in console, it works. So how to trigger it when script loaded? I new to javascript. Thanks and sry for my english.

function HotKeys() {
$('#msgbox').keydown(function (e) {
    if (e.ctrlKey && e.keyCode == 13) {
        document.getElementById("go").click();
    }
});
}     
HotKeys();

3 Answers3

0

You can trigger the function on load by using: window.onload = HotKeys();

If you want the function to be run anytime the hot keys are pressed, remove the function declaration around it so you just have the function body

wahiddudin
  • 103
  • 6
0

Don't use a function, but attach a document ready handler like that:

$(document).ready(function() {
    $("#msgbox").keydown(function (e) {
        if (e.ctrlKey && e.keyCode == 13) {
            $("#go").click();
        }
    });
});

This will register your handler when the document is ready. with your code, you indeed had to call HotKeys in order to register the handler.

Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158
  • You're welcome. But, as a reminder, you should tick answers that did work for you as accepted (you can upvote good answers if you wish too). I'm telling you this because I noticed you didn't mark any of your questions as resolved so far. And it gives you +2 rep ;) – Lucas Trzesniewski Jun 29 '14 at 21:01
0

try this

(function HotKeys() {
    $('#msgbox').keydown(function (e) {
        // when user presses ctrl + enter, click the "go" button
        if (e.ctrlKey && e.keyCode == 13) {
            document.getElementById("go").click();
        }
    }); 
})();
Ryan Wheale
  • 26,022
  • 8
  • 76
  • 96
akbarian
  • 51
  • 8