Jerome
Jerome

Reputation: 1192

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)

Upvotes: 0

Views: 431

Answers (2)

mutdmour
mutdmour

Reputation: 543

You could use Template events to do the same:

Template.home.events({
   'keydown':function(event){
       ...
   },
   'keypress #tftextinput': function(event){
       ...
   }
});

Upvotes: 2

Sagar V
Sagar V

Reputation: 12478

Try on window

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

Upvotes: 2

Related Questions