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.
...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...
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>
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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With