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?
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');
});
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) {...});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With