Reactively watch the element width


#1

How to reactively watch for an element width change ?
For example, if the element would change its width, I want to change its height reactively?

My code so far:

Template.photosListPhoto.onCreated(function () {
  this.elementWidth = new ReactiveVar();
});

Template.photosListPhoto.onRendered(function () {
  var self = this;

  self.autorun(function () {
    var currentWidth = self.$('li').width();
    self.elementWidth.set(currentWidth);
  });
});

Template.photosListPhoto.helpers({
  computedHeight: function () {
    var ratio = this.width / this.height;

    return Template.instance().elementWidth.get() / ratio;
  }
});

This is not reactive & does not update in autorun function, only on first run.

Any advices/thoughts?


#2

Replace the autorun with a window resize event handler to set the width on the reactive variable then it will work. Make sure to tear it down though onDestroyed.


#3

Thanks, this shall work. It seems tricky, but it seems to be the only way to do such stuff ?