Ben Taitelbaum
Ben Taitelbaum

Reputation: 7403

How can I handle key events in meteor?

According to the docs, I should be able to handle key events like keypress in the same way I can handle the click event, but I feel like I'm missing something.

I've done the following:

> meteor create keypressTest
> cd keypressTest
> sed -e 's/click input/keypress body/' -i .bak keypressTest.js
> meteor

But when I press keys, nothing shows up in the console like it does when handling the click event.

Are there any examples of working key handling in meteor? I know I can do a workaround in jquery, but would prefer to stick to the clean template events if I can.

Upvotes: 5

Views: 16736

Answers (4)

zeroasterisk
zeroasterisk

Reputation: 2209

I can find my 'keypress' events

Template.myTemplate.events({
    'keypress input': function(e) { console.log('key', e); }
});

or in a more usable example

Template.myTemplate.events({
      'keyup input': function(event) {
      if (event.which === 13) {
         alert('you hit enter');
         event.stopPropagation();
         return false;
      }
   },
    ...

@tom, I didn't get anything on textinput :(

Upvotes: 8

MichelH
MichelH

Reputation: 385

Enter will return an event.charCode = 0, instead use event.keyCode this will return 13.

'keypress input': function(event) {
    if (event.keyCode == 13) {
        alert('you hit enter');
        event.stopPropagation();
        return false;
    }
}

Upvotes: 1

Ben Taitelbaum
Ben Taitelbaum

Reputation: 7403

I was missing these two requirements for using key events in the eventmap:

  1. The event target must be contained within the template (same as other events)
  2. The event target must be an input element that can be typed in

The second point seems consistent with clicking, since a click * only fires when clicking on the button, not on the greeting text also contained within the template.

Upvotes: 5

Tamara Wijsman
Tamara Wijsman

Reputation: 12348

Please note that keypress is deprecated and you might want to use textinput instead.

I do however note that keydown and keyup are not deprecated, so using one of those might work more reliable than using keypress. Note that the documentation specifies the order:

  1. keydown
  2. keypress
  3. keyup

If you want to act upon the press you could use keydown; if you want to act upon the lift, use keyup. I would prefer the latter given that it still allows you to cancel the keypress by switching to another application before lifting it...

Upvotes: 11

Related Questions