Question

I am working on a chat app built with Meteor based off of this tutorial (http://code.tutsplus.com/tutorials/real-time-messaging-for-meteor-with-meteor-streams--net-33409) and I am trying to make it where if you press enter it submits your message instead of having to press the Send button.

Below is the javascript code the app uses to submit a comment by pressing the Send button, but does anyone know how to add the enter feature?

// when Send Chat clicked add the message to the collection
Template.chatBox.events({
  "click #send": function() {
    var message = $('#chat-message').val();
    chatCollection.insert({
     userId: 'me',
     message: message
   });
   $('#chat-message').val('');

   //add the message to the stream
   chatStream.emit('chat', message);
  }
});
chatStream.on('chat', function(message) {
  chatCollection.insert({
    userId: this.userId,
    subscriptionId: this.subscriptionId,
    message: message
  });
});
Was it helpful?

Solution

You need to check for a key press event. You can find a full list of the codes for each key here: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

Best way to do this would be make the function in the click event a named function and then you can just run the same function on both events.

Template.chatBox.events({
 "click #send": function() {
    var message = $('#chat-message').val();
    chatCollection.insert({
      userId: 'me',
      message: message
    });
    $('#chat-message').val('');

    //add the message to the stream
    chatStream.emit('chat', message);
  },
  "keypress #chat-message": function(e) { 
    if (e.which == 13) {
      console.log("you pressed enter");
      //repeat function from #send click event here
     }
  }
});

OTHER TIPS

'keypress #send': function (evt) {
     if (evt.which === 13) {

13 is the keycode for enter. If you want to change it you can look up the javascript keycodes so you can bind to whatever you like.

You might want to consider familiarizing yourself with the api http://docs.meteor.com/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top