Search code examples
polymerweb-component

How to get the width of a polymer element inside the JS of the polymer element


I have a polymer element and inside its Javascript I am trying to find its width and height as it is inside the DOM. I tried many ways but I always get 0 back.


Solution

  • ...and here's the one which works for me:

    Add the Polymer.IronResizableBehavior behaviour to your element (see https://elements.polymer-project.org/elements/iron-resizable-behavior). Then your element will be sent a iron-resize event when it gets sized. In the handler, check to see whether it's not 0; if not, you're golden.

    Untested code follows:

    <dom-module id="hard-chicken">
      <template>
        Hello <span>{{name}}</span>
      </template>
    </dom-module>
    <script>
      Polymer({
        is: 'hard-chicken',
        behaviors: [ Polymer.IronResizableBehavior ],
        listeners: { "iron-resize": "onWidthChange" },
        onWidthChange: function() {
          var w = this.offsetWidth;
          if (w > 0)
            console.log("width is now ", w);
        }
      });
    </script>
    

    This took way, way too long to figure out...