Search code examples
javascriptmeteorlistenerkeypress

How to listen the key pressed on all the document using JavaScript and Meteor template?


I have founded that if I want to listen on all the document I should do :

$(document).keydown(function(e) {
          console.log(e);
          console.log(e.keyCode);
             if (e.keyCode == 27) {
               $('#tftextinput').value="";
               $('#tfbutton').click();
            }
});

but it doesn't write anything in the console... So I have tried an other version like this:

$(".container.body").keydown(function(e) {
          console.log(e);
          console.log(e.keyCode);
             if (e.keyCode == 27) {
               $('#tftextinput').value="";
               $('#tfbutton').click();
            }
 });

this code is in the $(document).ready(function() {}); but nothing happened too...

enter image description here

EDIT:

If I write this code in the web console it works: enter image description here

So why it doesn't work in my Meteor template code ?

Template.home.onRendered(function() {
    $(document).ready(function() {
        /*
        this method listen if we press "enter" in the research field and click on the button
        */
        $('#tftextinput').keypress(function(e) {
            if (e.keyCode == 13) {
                $('#tfbutton').click();
            }
        });
        $(document).keydown(function(e) {
          console.log(e);
          console.log(e.keyCode);
             if (e.keyCode == 27) {
               $('#tftextinput').value="";
               $('#tfbutton').click();
            }
        });
    });
});

the first listener works (the one who listens tftextinput)


Solution

  • Try on window

    $(window).on("keydown",function(e) {
              console.log(e);
              console.log(e.keyCode);
                 if (e.keyCode == 27) {
                   $('#tftextinput').value="";
                   $('#tfbutton').click();
                }
     });