Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor keydown/keyup events outside input

Tags:

meteor

After reading this thread: Keypress events stopped working outside of "input" elements in Meteor after update to 0.5.2

I understand that keydown/keyup events are not possible unless you add it to $(document).on('keyup')..... inside the Rendered callback.

But that thread is over 2 years old. Is this still the case? Is there still no "Meteor Way" of adding a keyup/keydown event outside input/contenteditable?

like image 705
Mcope Avatar asked Dec 05 '22 23:12

Mcope


2 Answers

The answer to your question is yes, it can still be done that way. You can still make key event listeners for single templates by adding the event listener in the onCreated or onRendered methods like so:

Template.myTemplate.onCreated(() => {
    $(document).on('keyup', (e) => {
        console.log('A key has come up.');
    });
});

You do not have to do it in Meteor.startup as suggested by the currently accepted answer.

To destroy the event so that it doesn't persist when no longer within this template:

Template.myTemplate.onDestroyed(() => {
    $(document).off('keyup');
});
like image 188
Nate Avatar answered Feb 11 '23 00:02

Nate


If you want to add a keyup event for the whole page on page load, the "meteor way" is to use Meteor.startup:

Meteor.startup(function () {
  $(document).on('keyup', function (e) {...});
}
like image 39
stubailo Avatar answered Feb 11 '23 02:02

stubailo