Encore PTL
Encore PTL

Reputation: 8214

Meteor publishing information from server changes DOM and removes keyboard focus on the element

I am trying to build an app like Google Docs that contains webpage with a textarea and on changing of the value I publish and update to the server and get back the response of the save from the server which updates the DOM.

The issue is that the updating of the DOM which happens later removes the textarea focus which user needs to keep typing. The focus is lost and the user has to click on the textarea again to gain focus and keep typing.

How can I overcome this issue of losing focus when a value is changed remotely on the server and sent to the client.

Upvotes: 1

Views: 102

Answers (2)

jusynth
jusynth

Reputation: 191

Have you tried wrapping the element in {{#constant}} {{/constant}} tags?

Upvotes: 1

David Weldon
David Weldon

Reputation: 64342

You can use a session variable and the rendered callback on your template to do this. Here is a really simple example using a template with one textarea:

<template name="home">
  <textarea></textarea>
</template>
Template.home.events({
  'focus textarea': function() {
    Session.set('hasFocus', true);
  },
  'blur textarea': function() {
    Session.set('hasFocus', false);
  }
});

Template.home.rendered = function() {
  if (Session.get('hasFocus')) {
    $('textarea').focus();
  }
};

Template.home.destroyed = function() {
  return Session.set('hasFocus', undefined);
};

When you focus or blur the textarea, we modify the session variable hasFocus. Whenever the template is rendered we just focus the textarea based on the same variable. When we are done with the template, just clean up hasFocus so it doesn't interfere with other pages.

Upvotes: 1

Related Questions