Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 733
Phil Avatar asked Jul 17 '15 04:07

Phil


4 Answers

...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...

like image 160
David Given Avatar answered Jan 04 '23 21:01

David Given


polymer 1.0

<link rel="import" href="../polymer/polymer.html">

<!-- 
Here's where you'll define your element. You can define multiple elements
if you want, but the package name will be taken from the first custom
element you define in the file. You can also document your element! For
more info, see [the docs](https://ele.io/docs).

@element hard-chicken
-->
<dom-module id="hard-chicken" attributes="name">
  <template>
    <style>
      :host {
        font-family: sans-serif;
      }
    </style>
    Hello {{name}}
  </template>
  <script>
    Polymer({is:'hard-chicken', 
      /**
       * The name of the person you want to say hello to.
       * @attribute name
       * @type string
       * @default "Polymer Dev"
       */
      name: 'Polymer Dev',
      ready: function() {
        console.log(this.offsetWidth);
    });
  </script>
</dom-module>
like image 21
sujkh85 Avatar answered Jan 04 '23 21:01

sujkh85


You probably want to calculate the width in the attached handler of the element, as that comes last when the unit is actually attached to the DOM.

See https://www.polymer-project.org/1.0/docs/devguide/registering-elements.html#initialization-order

attached: function() {
  console.log(this.offsetWidth);
}
like image 44
Adam Heath Avatar answered Jan 04 '23 20:01

Adam Heath


This should do it:

attached: function() {
  this.async(function() {
    console.log(this.offsetWidth);
  });
}

Read the documentation at: https://www.polymer-project.org/1.0/docs/devguide/registering-elements#initialization-order

like image 42
cdn34 Avatar answered Jan 04 '23 20:01

cdn34