Hassan Hayat
Hassan Hayat

Reputation: 1065

How do you observe the width of an element in polymer?

I was wondering how it is possible to observe changes to an element's css property such as the width.

I tried doing this but it didn't work. Where did I go wrong? Is it possible?

<polymer-element name="test-resize" attributes="elementWidth">
  <template>
    <p>elementWidth : {{elementWidth}}</p>
  </template>
  <script>
    Polymer({
      elementWidth: 100,
      observe: {
        "clientWidth" : "updateWidth",
      },
      updateWidth: function(oldValue, newValue){
        this.elementWidth = newValue;
      }
    });
  </script>
</polymer-element>

In this example, I'm trying to observe the clientWidth property which you can normally access from outside.

Upvotes: 0

Views: 1916

Answers (1)

Winchestro
Winchestro

Reputation: 2188

There is a certain technique abusing CSS transitions and listening for the transitionend event. There are only a very few cases where it's really required (like if you want to adjust the resolution of a webgl context after the canvas dimensions changed in any way)

Add a transition in css to make the transition event fire when width/height change.

:host {
  transition:width 0.01s, height 0.01s;
}

Listen for the event and handle whatever you want to happen

this.addEventListener("transitionend",function(e){
  this.elementWidth = this.clientWidth;
}) 

more info about implementing the technique, like polyfills you'll probably need

Upvotes: 5

Related Questions